SlideShare ist ein Scribd-Unternehmen logo
1 von 27
JavaScript in Drupal 7:

WHAT DEVELOPERS NEED TO KNOW




                               October 24th, 2009
PROBLEM:

jQuery’s use of the $ can interfere with other
libraries.

D6:
$(document).ready(function(){

      ....

});


                                         October 24th, 2009
SOLUTION:

Wrap everthing in the following:


(function($) {

  ....

})(jQuery);




                                   October 24th, 2009
PROBLEM:

Not enough flexibility in how we can add js to our Drupal pages:

 - can’t fully control the ordering of js files

 - can’t load external js

D6:

drupal_add_js(‘path/to/some_js_file.js’, ‘module’, ‘header’);




                                                  October 24th, 2009
SOLUTION:

drupal_add_js() now allows you to add a weight value to each script
you’re adding:
  - JS_LIBRARY: Any libraries, settings, or jQuery plugins.
  - JS_DEFAULT: Any module-layer JavaScript.
  - JS_THEME: Any theme-layer JavaScript.

 drupal_add_js('jQuery(document).ready(function ()
{ alert("Hello!"); });', array('type' => 'inline', 'scope' => 'footer',
'weight' => 5);



                                                          October 24th, 2009
SOLUTION:

drupal_add_js() allows you to load external js files:

drupal_add_js('http://example.com/example.js', 'external');




                                                       October 24th, 2009
PROBLEM:

Some JavaScript code is being provided by core or some contrib
module but it’s not the most up-to-date version.




                                                 October 24th, 2009
SOLUTION:

hook_js_alter()

function hook_js_alter(&$javascript) {
  // Swap out jQuery to use an updated version of the library.
  $javascript['misc/jquery.js']['data'] = drupal_get_path('module',
'jquery_update') . '/jquery.js';
}




                                                             October 24th, 2009
Renderable arrays and #attached js:


function render_my_content() {
  $build['myelement'] = array(
    '#theme' => 'my_theme_function',
    '#myvar' => $myvar,
    '#attached' => array('js' => drupal_get_path('module', 'mymodule') .
'/myjs.js', 'css' => drupal_get_path('module', 'mymodule') . '/
styles.css'),
  );
  $output = drupal_render($build);
  return $output;
}




                                                      October 24th, 2009
PROBLEM:

There’s no standard way of adding collections of JavaScript and
CSS, such as jQuery plugins




                                                  October 24th, 2009
SOLUTION: Libraries
                      function system_library() {
                        ...
                        // Vertical Tabs.
                        $libraries['vertical-tabs'] = array(
                           'title' => 'Vertical Tabs',
                           'website' => 'http://drupal.org/node/323112',
                           'version' => '1.0',
hook_library()             'js' => array(
                              'misc/vertical-tabs.js' => array(),
                           ),
                           'css' => array(
                              'misc/vertical-tabs.css' => array(),
                           ),
                        );
                        ...
                        return $libraries;
                      }




                                                          October 24th, 2009
function mymodule_library() {
SOLUTION: Libraries     $libraries['mylibrary'] = array(
                           'title' => 'An Awesome Library',
                           'website' => 'http://example.com/library',
                           'version' => '3.1-beta1',
                           'js' => array(
                              // JavaScript settings may use the 'data' key.
                              array(
                                 'type' => 'setting',
                                 'data' => array('mylibrary' => TRUE),
hook_library()                ),
                           ),
                           'dependencies' => array(
                              // Require jQuery UI core by System module.
                              array('system' => 'ui'),
                              // Require our other library.
                              array('mymodule', 'library-1'),
                              // Require another library.
                              array('other_module', 'library-2'),
                           ),
                        );
                        return $libraries;
                      }


                                                          October 24th, 2009
SOLUTION: Libraries

                        function theme_vertical_tabs($variables) {
                          $element = $variables['element'];
                          // Add required JavaScript and Stylesheet.
                          drupal_add_library('system', 'vertical-
drupal_add_libarary()   tabs');

                          return '<div class="vertical-tabs-panes">' .
                        $element['#children'] . '</div>';
                        }




                                                  October 24th, 2009
PROBLEM:

AHAH forms make people want to jump out the window of very tall
buildings




                                               October 24th, 2009
AHAH in D6.... ugh!
function quicktabs_ahah() {
  $form_state = array('storage' => NULL, 'submitted' => FALSE);
  $form_build_id = $_POST['form_build_id'];
  $form = form_get_cache($form_build_id, $form_state);
  $args = $form['#parameters'];
  $form_id = array_shift($args);
  $form['#post'] = $_POST;
  $form['#redirect'] = FALSE;
  $form['#programmed'] = FALSE;
  $form_state['post'] = $_POST;
  drupal_process_form($form_id, $form, $form_state);
  $form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id);
  $qt_form = $form['qt_wrapper']['tabs'];
  unset($qt_form['#prefix'], $qt_form['#suffix']); // Prevent duplicate wrappers.
  $javascript = drupal_add_js(NULL, NULL, 'header');
  drupal_json(array(
    'status'   => TRUE,
    'data'     => theme('status_messages') . drupal_render($qt_form),
    'settings' => call_user_func_array('array_merge_recursive',
$javascript['setting']),
  ));
}


                                                                         October 24th, 2009
AJAX in D7.... :-)




function quicktabs_ajax($form, $form_state) {
  $form_tabs = $form['qt_wrapper']['tabs'];
  $output = drupal_render($form_tabs);
  return $output;
}




                                                October 24th, 2009
SOLUTION:

There’s now a framework for ajax in Drupal

Merlinofchaos has done all the hard work, so you don’t have to! :-)




                                                       October 24th, 2009
PROBLEM:

Ajax-loaded content doesn’t get behaviors attached to it if they
depend on Drupal.settings




                                                   October 24th, 2009
SOLUTION:

Drupal.attachBehaviors now takes a second parameter, which is the
local settings for the portion of the DOM it’s attaching behaviors to:

Drupal.attachBehaviors(context, settings)




                                                        October 24th, 2009
To have the settings available for your ajax-loaded content:

- your ajax callback must make a call to drupal_add_js to grab the
JavaScript for the output it’s rendering

- it must return the settings array as part of its response

- when your ajax success function makes a call to
Drupal.attachBehaviors, it must pass in the settings from the
response.




                                                    October 24th, 2009
function quicktabs_ajax_qtabs($qtid) {
  $tabpage = array(
    'type' => 'qtabs',
    'qtid' => $qtid,
  );

  $output = quicktabs_render_tabpage($tabpage);

  $scripts = drupal_add_js(NULL, NULL);
  $settings = call_user_func_array('array_merge_recursive', $scripts['settings']
['data']);
  drupal_json_output(array('status' => TRUE, 'data' => $output, 'settings' =>
$settings));
}




                                                             October 24th, 2009
Drupal.quicktabs.tab.prototype.success = function(response) {
  var result = Drupal.parseJson(response.data);
  this.container.append(Drupal.theme('quicktabsResponse', this,
result));
  Drupal.attachBehaviors(this.container, response.settings);
}




                                                 October 24th, 2009
Drupal.behaviors.quicktabs = {
  attach: function (context, settings) {
    $.extend(true, Drupal.settings, settings);
    $('.quicktabs_wrapper:not(.quicktabs-processed)',
context).addClass('quicktabs-processed').each(function(){
      Drupal.quicktabs.prepare(this);
    });
  }
}




                                               October 24th, 2009
jQuery UI is in core

- accordion            - progressbar   effects:

- datepicker           - resizable     - bounce

- dialog               - selectable    - explode

- draggable            - sortable      - fold

- droppable            - tabs          - pulsate



                                           October 24th, 2009
jQuery UI is in core
function render_accordion_block() {
  $build['myelement'] = array(
    '#theme' => 'my_accordion',
  );
  $build['myelement']['#attached']['library'][] = array('system',
'ui.accordion');
  $build['myelement']['#attached']['js'][] = array('data' =>
'(function($){$(function() { $("#accordion").accordion(); })})(jQuery);',
'type' => 'inline');
  $output = drupal_render($build);
  return $output;
}




                                                      October 24th, 2009
Miscellaneous Changes:

- Drupal.behaviors are now attached and detached

- drupal_to_js is now drupal_json_encode

- drupal_json is now drupal_json_output

- use jQuery.once() to attach a behaviour once




                                                   October 24th, 2009
QUESTIONS?




             October 24th, 2009

Weitere ähnliche Inhalte

Was ist angesagt?

Drupal Development
Drupal DevelopmentDrupal Development
Drupal DevelopmentJeff Eaton
 
Drupal Development (Part 2)
Drupal Development (Part 2)Drupal Development (Part 2)
Drupal Development (Part 2)Jeff Eaton
 
JavaScript for Flex Devs
JavaScript for Flex DevsJavaScript for Flex Devs
JavaScript for Flex DevsAaronius
 
Drupal Step-by-Step: How We Built Our Training Site, Part 1
Drupal Step-by-Step: How We Built Our Training Site, Part 1Drupal Step-by-Step: How We Built Our Training Site, Part 1
Drupal Step-by-Step: How We Built Our Training Site, Part 1Acquia
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2zfconfua
 
AngularJS Services
AngularJS ServicesAngularJS Services
AngularJS ServicesEyal Vardi
 
How Not to Build a WordPress Plugin
How Not to Build a WordPress PluginHow Not to Build a WordPress Plugin
How Not to Build a WordPress PluginWill Norris
 
Backbone js in drupal core
Backbone js in drupal coreBackbone js in drupal core
Backbone js in drupal coreMarcin Wosinek
 
jQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
jQuery UI Widgets, Drag and Drop, Drupal 7 JavascriptjQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
jQuery UI Widgets, Drag and Drop, Drupal 7 JavascriptDarren Mothersele
 
Drupal Module Development
Drupal Module DevelopmentDrupal Module Development
Drupal Module Developmentipsitamishra
 
AngulrJS Overview
AngulrJS OverviewAngulrJS Overview
AngulrJS OverviewEyal Vardi
 
Анатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to zАнатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to zLEDC 2016
 
Drupal 8: Forms
Drupal 8: FormsDrupal 8: Forms
Drupal 8: Formsdrubb
 
Introduction to backbone presentation
Introduction to backbone presentationIntroduction to backbone presentation
Introduction to backbone presentationBrian Hogg
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ EtsyNishan Subedi
 
Drupal 8: Routing & More
Drupal 8: Routing & MoreDrupal 8: Routing & More
Drupal 8: Routing & Moredrubb
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for JoomlaLuke Summerfield
 

Was ist angesagt? (20)

Drupal Development
Drupal DevelopmentDrupal Development
Drupal Development
 
Drupal Development (Part 2)
Drupal Development (Part 2)Drupal Development (Part 2)
Drupal Development (Part 2)
 
JavaScript for Flex Devs
JavaScript for Flex DevsJavaScript for Flex Devs
JavaScript for Flex Devs
 
Drupal Step-by-Step: How We Built Our Training Site, Part 1
Drupal Step-by-Step: How We Built Our Training Site, Part 1Drupal Step-by-Step: How We Built Our Training Site, Part 1
Drupal Step-by-Step: How We Built Our Training Site, Part 1
 
Drupal 8: Fields reborn
Drupal 8: Fields rebornDrupal 8: Fields reborn
Drupal 8: Fields reborn
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2
 
AngularJS Services
AngularJS ServicesAngularJS Services
AngularJS Services
 
How Not to Build a WordPress Plugin
How Not to Build a WordPress PluginHow Not to Build a WordPress Plugin
How Not to Build a WordPress Plugin
 
Backbone js in drupal core
Backbone js in drupal coreBackbone js in drupal core
Backbone js in drupal core
 
jQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
jQuery UI Widgets, Drag and Drop, Drupal 7 JavascriptjQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
jQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
 
Drupal Module Development
Drupal Module DevelopmentDrupal Module Development
Drupal Module Development
 
AngulrJS Overview
AngulrJS OverviewAngulrJS Overview
AngulrJS Overview
 
Анатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to zАнатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to z
 
An Introduction to Drupal
An Introduction to DrupalAn Introduction to Drupal
An Introduction to Drupal
 
Drupal 8 Services
Drupal 8 ServicesDrupal 8 Services
Drupal 8 Services
 
Drupal 8: Forms
Drupal 8: FormsDrupal 8: Forms
Drupal 8: Forms
 
Introduction to backbone presentation
Introduction to backbone presentationIntroduction to backbone presentation
Introduction to backbone presentation
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
Drupal 8: Routing & More
Drupal 8: Routing & MoreDrupal 8: Routing & More
Drupal 8: Routing & More
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
 

Ähnlich wie JavaScript in Drupal 7: What developers need to know

JQuery In Drupal
JQuery In DrupalJQuery In Drupal
JQuery In Drupalkatbailey
 
What's new in the Drupal 7 API?
What's new in the Drupal 7 API?What's new in the Drupal 7 API?
What's new in the Drupal 7 API?Alexandru Badiu
 
8 things to know about theming in drupal 8
8 things to know about theming in drupal 88 things to know about theming in drupal 8
8 things to know about theming in drupal 8Logan Farr
 
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011camp_drupal_ua
 
Drupal 7 Theming - Behind the scenes
Drupal 7 Theming - Behind the scenes Drupal 7 Theming - Behind the scenes
Drupal 7 Theming - Behind the scenes ramakesavan
 
SilverStripe CMS JavaScript Refactoring
SilverStripe CMS JavaScript RefactoringSilverStripe CMS JavaScript Refactoring
SilverStripe CMS JavaScript RefactoringIngo Schommer
 
Keeping it Small: Getting to know the Slim Micro Framework
Keeping it Small: Getting to know the Slim Micro FrameworkKeeping it Small: Getting to know the Slim Micro Framework
Keeping it Small: Getting to know the Slim Micro FrameworkJeremy Kendall
 
Beyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance JavascriptBeyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance Javascriptaglemann
 
Debugging in drupal 8
Debugging in drupal 8Debugging in drupal 8
Debugging in drupal 8Allie Jones
 
WordPress for developers - phpday 2011
WordPress for developers -  phpday 2011WordPress for developers -  phpday 2011
WordPress for developers - phpday 2011Maurizio Pelizzone
 
Drupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency InjectionDrupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency InjectionPhilip Norton
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For BeginnersJonathan Wage
 
Drupal 8 Theme System: The Backend of Frontend
Drupal 8 Theme System: The Backend of FrontendDrupal 8 Theme System: The Backend of Frontend
Drupal 8 Theme System: The Backend of FrontendAcquia
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)arcware
 
DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7chuvainc
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJSAaronius
 
Demystifying AJAX Callback Commands in Drupal 8
Demystifying AJAX Callback Commands in Drupal 8Demystifying AJAX Callback Commands in Drupal 8
Demystifying AJAX Callback Commands in Drupal 8Michael Miles
 
In-depth changes to Drupal 8 javascript
In-depth changes to Drupal 8 javascriptIn-depth changes to Drupal 8 javascript
In-depth changes to Drupal 8 javascriptThéodore Biadala
 

Ähnlich wie JavaScript in Drupal 7: What developers need to know (20)

JQuery In Drupal
JQuery In DrupalJQuery In Drupal
JQuery In Drupal
 
What's new in the Drupal 7 API?
What's new in the Drupal 7 API?What's new in the Drupal 7 API?
What's new in the Drupal 7 API?
 
8 things to know about theming in drupal 8
8 things to know about theming in drupal 88 things to know about theming in drupal 8
8 things to know about theming in drupal 8
 
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
 
Drupal 7 Theming - Behind the scenes
Drupal 7 Theming - Behind the scenes Drupal 7 Theming - Behind the scenes
Drupal 7 Theming - Behind the scenes
 
SilverStripe CMS JavaScript Refactoring
SilverStripe CMS JavaScript RefactoringSilverStripe CMS JavaScript Refactoring
SilverStripe CMS JavaScript Refactoring
 
Keeping it Small: Getting to know the Slim Micro Framework
Keeping it Small: Getting to know the Slim Micro FrameworkKeeping it Small: Getting to know the Slim Micro Framework
Keeping it Small: Getting to know the Slim Micro Framework
 
Beyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance JavascriptBeyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance Javascript
 
Debugging in drupal 8
Debugging in drupal 8Debugging in drupal 8
Debugging in drupal 8
 
WordPress for developers - phpday 2011
WordPress for developers -  phpday 2011WordPress for developers -  phpday 2011
WordPress for developers - phpday 2011
 
Drupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency InjectionDrupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency Injection
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Drupal 8 Theme System: The Backend of Frontend
Drupal 8 Theme System: The Backend of FrontendDrupal 8 Theme System: The Backend of Frontend
Drupal 8 Theme System: The Backend of Frontend
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
 
DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
 
Demystifying AJAX Callback Commands in Drupal 8
Demystifying AJAX Callback Commands in Drupal 8Demystifying AJAX Callback Commands in Drupal 8
Demystifying AJAX Callback Commands in Drupal 8
 
In-depth changes to Drupal 8 javascript
In-depth changes to Drupal 8 javascriptIn-depth changes to Drupal 8 javascript
In-depth changes to Drupal 8 javascript
 

Kürzlich hochgeladen

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 

Kürzlich hochgeladen (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 

JavaScript in Drupal 7: What developers need to know

  • 1. JavaScript in Drupal 7: WHAT DEVELOPERS NEED TO KNOW October 24th, 2009
  • 2. PROBLEM: jQuery’s use of the $ can interfere with other libraries. D6: $(document).ready(function(){ .... }); October 24th, 2009
  • 3. SOLUTION: Wrap everthing in the following: (function($) { .... })(jQuery); October 24th, 2009
  • 4. PROBLEM: Not enough flexibility in how we can add js to our Drupal pages: - can’t fully control the ordering of js files - can’t load external js D6: drupal_add_js(‘path/to/some_js_file.js’, ‘module’, ‘header’); October 24th, 2009
  • 5. SOLUTION: drupal_add_js() now allows you to add a weight value to each script you’re adding: - JS_LIBRARY: Any libraries, settings, or jQuery plugins. - JS_DEFAULT: Any module-layer JavaScript. - JS_THEME: Any theme-layer JavaScript. drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5); October 24th, 2009
  • 6. SOLUTION: drupal_add_js() allows you to load external js files: drupal_add_js('http://example.com/example.js', 'external'); October 24th, 2009
  • 7. PROBLEM: Some JavaScript code is being provided by core or some contrib module but it’s not the most up-to-date version. October 24th, 2009
  • 8. SOLUTION: hook_js_alter() function hook_js_alter(&$javascript) { // Swap out jQuery to use an updated version of the library. $javascript['misc/jquery.js']['data'] = drupal_get_path('module', 'jquery_update') . '/jquery.js'; } October 24th, 2009
  • 9. Renderable arrays and #attached js: function render_my_content() {   $build['myelement'] = array(     '#theme' => 'my_theme_function',     '#myvar' => $myvar,     '#attached' => array('js' => drupal_get_path('module', 'mymodule') . '/myjs.js', 'css' => drupal_get_path('module', 'mymodule') . '/ styles.css'),   );   $output = drupal_render($build);   return $output; } October 24th, 2009
  • 10. PROBLEM: There’s no standard way of adding collections of JavaScript and CSS, such as jQuery plugins October 24th, 2009
  • 11. SOLUTION: Libraries function system_library() { ... // Vertical Tabs. $libraries['vertical-tabs'] = array( 'title' => 'Vertical Tabs', 'website' => 'http://drupal.org/node/323112', 'version' => '1.0', hook_library() 'js' => array( 'misc/vertical-tabs.js' => array(), ), 'css' => array( 'misc/vertical-tabs.css' => array(), ), ); ... return $libraries; } October 24th, 2009
  • 12. function mymodule_library() { SOLUTION: Libraries $libraries['mylibrary'] = array( 'title' => 'An Awesome Library', 'website' => 'http://example.com/library', 'version' => '3.1-beta1', 'js' => array( // JavaScript settings may use the 'data' key. array( 'type' => 'setting', 'data' => array('mylibrary' => TRUE), hook_library() ), ), 'dependencies' => array( // Require jQuery UI core by System module. array('system' => 'ui'), // Require our other library. array('mymodule', 'library-1'), // Require another library. array('other_module', 'library-2'), ), ); return $libraries; } October 24th, 2009
  • 13. SOLUTION: Libraries function theme_vertical_tabs($variables) { $element = $variables['element']; // Add required JavaScript and Stylesheet. drupal_add_library('system', 'vertical- drupal_add_libarary() tabs'); return '<div class="vertical-tabs-panes">' . $element['#children'] . '</div>'; } October 24th, 2009
  • 14. PROBLEM: AHAH forms make people want to jump out the window of very tall buildings October 24th, 2009
  • 15. AHAH in D6.... ugh! function quicktabs_ahah() {   $form_state = array('storage' => NULL, 'submitted' => FALSE);   $form_build_id = $_POST['form_build_id'];   $form = form_get_cache($form_build_id, $form_state);   $args = $form['#parameters'];   $form_id = array_shift($args);   $form['#post'] = $_POST;   $form['#redirect'] = FALSE;   $form['#programmed'] = FALSE;   $form_state['post'] = $_POST;   drupal_process_form($form_id, $form, $form_state);   $form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id);   $qt_form = $form['qt_wrapper']['tabs'];   unset($qt_form['#prefix'], $qt_form['#suffix']); // Prevent duplicate wrappers.   $javascript = drupal_add_js(NULL, NULL, 'header');   drupal_json(array(     'status'   => TRUE,     'data'     => theme('status_messages') . drupal_render($qt_form),     'settings' => call_user_func_array('array_merge_recursive', $javascript['setting']),   )); } October 24th, 2009
  • 16. AJAX in D7.... :-) function quicktabs_ajax($form, $form_state) {   $form_tabs = $form['qt_wrapper']['tabs'];   $output = drupal_render($form_tabs);   return $output; } October 24th, 2009
  • 17. SOLUTION: There’s now a framework for ajax in Drupal Merlinofchaos has done all the hard work, so you don’t have to! :-) October 24th, 2009
  • 18. PROBLEM: Ajax-loaded content doesn’t get behaviors attached to it if they depend on Drupal.settings October 24th, 2009
  • 19. SOLUTION: Drupal.attachBehaviors now takes a second parameter, which is the local settings for the portion of the DOM it’s attaching behaviors to: Drupal.attachBehaviors(context, settings) October 24th, 2009
  • 20. To have the settings available for your ajax-loaded content: - your ajax callback must make a call to drupal_add_js to grab the JavaScript for the output it’s rendering - it must return the settings array as part of its response - when your ajax success function makes a call to Drupal.attachBehaviors, it must pass in the settings from the response. October 24th, 2009
  • 21. function quicktabs_ajax_qtabs($qtid) {   $tabpage = array(     'type' => 'qtabs',     'qtid' => $qtid,   );   $output = quicktabs_render_tabpage($tabpage);   $scripts = drupal_add_js(NULL, NULL);   $settings = call_user_func_array('array_merge_recursive', $scripts['settings'] ['data']);   drupal_json_output(array('status' => TRUE, 'data' => $output, 'settings' => $settings)); } October 24th, 2009
  • 22. Drupal.quicktabs.tab.prototype.success = function(response) {   var result = Drupal.parseJson(response.data);   this.container.append(Drupal.theme('quicktabsResponse', this, result));   Drupal.attachBehaviors(this.container, response.settings); } October 24th, 2009
  • 23. Drupal.behaviors.quicktabs = {   attach: function (context, settings) {     $.extend(true, Drupal.settings, settings);     $('.quicktabs_wrapper:not(.quicktabs-processed)', context).addClass('quicktabs-processed').each(function(){       Drupal.quicktabs.prepare(this);     });   } } October 24th, 2009
  • 24. jQuery UI is in core - accordion - progressbar effects: - datepicker - resizable - bounce - dialog - selectable - explode - draggable - sortable - fold - droppable - tabs - pulsate October 24th, 2009
  • 25. jQuery UI is in core function render_accordion_block() {   $build['myelement'] = array(     '#theme' => 'my_accordion',   );   $build['myelement']['#attached']['library'][] = array('system', 'ui.accordion');   $build['myelement']['#attached']['js'][] = array('data' => '(function($){$(function() { $("#accordion").accordion(); })})(jQuery);', 'type' => 'inline');   $output = drupal_render($build);   return $output; } October 24th, 2009
  • 26. Miscellaneous Changes: - Drupal.behaviors are now attached and detached - drupal_to_js is now drupal_json_encode - drupal_json is now drupal_json_output - use jQuery.once() to attach a behaviour once October 24th, 2009
  • 27. QUESTIONS? October 24th, 2009