Last updated June 24, 2014. Created by katbailey on September 5, 2008.
Edited by balintk, danylevskyi, clemens.tolboom, Pere Orga. Log in to edit this page.
This page is a description of how JavaScript is implemented in Drupal, including an in-depth look at the drupal.js file and in particular the Drupal js object initialized therein.
Note: The following examples code are lacking JSDoc, only for clarity.
The very first line of JavaScript code in Drupal core, in drupal.js, is an Object declaration:
var Drupal = Drupal || { 'settings': {}, 'behaviors': {}, 'themes': {}, 'locale': {} };
In this code, Drupal is an Object declared to be equal to itself, or, if not yet set, equal to { 'settings': {}, 'behaviors': {}, 'themes': {}, 'locale': {} } which is an Object containing 4 properties (settings, behaviors, themes, and locale) each of which is itself an Object. This line of code is an Object Initializer. This Drupal object and its properties can then be used and extended by other modules. The best way to understand this is to look at the different properties one by one and the ways they are used by Drupal modules.
Jump to a section:
Drupal.settings
Drupal.behaviors
Drupal.theme
Drupal.locale
Drupal.settings
Drupal.settings is what enables us to pass information from our PHP code to our JavaScript code. This means you can change how your JavaScript behaves based on your module. For example, you may want to simply let JavaScript know what the base path is. In order to do this, you just create a PHP array of settings, as follows:
<?php
$my_settings = array(
'basePath' => $base_path,
'animationEffect' => variable_get('effect', 'none')
);
?>
Note: The array keys are set using CamelCasing according the JavaScript coding standards.
@see: https://drupal.org/node/172169#camelcasing
Then call drupal_add_js() (deprecated in Drupal 8) and pass in this array, with "setting" as your second parameter:
<?php
drupal_add_js(array('myModule' => $my_settings), 'setting');
?>
Note that it is further padded inside another array purely for namespacing purposes: another module might define the basePath setting as well. Now you can access these settings in your JavaScript code as follows:
var basePath = Drupal.settings.myModule.basePath;
var effect = Drupal.settings.myModule.animationEffect;
These are strings, but not string objects in JavaScript. The value of the array key you pass into drupal_add_js() will be concatenated to the end of this string separated by a comma.
Note: Drupal 7 passes the settings locally
Drupal.behaviors
When most of us learn jQuery for the first time, we learn to put all our code inside the $(document).ready() function, like this:
$(document).ready(function () {
// Do some fancy stuff.
});
This ensures that our code will get run as soon as the DOM has loaded, manipulating elements and binding behaviors to events as per our instructions. However, as of Drupal 6, we don't need to include the $(document).ready() function in our jQuery code at all. Instead we put all our code inside a function that we assign as a property of Drupal.behaviors. The Drupal.behaviors object is itself a property of the Drupal object, as explained above, and when we want our module to add new jQuery behaviors, we simply extend this object. The entire jQuery code for your module could be structured like this:
Drupal.behaviors.myModuleBehavior = function (context) {
//Do some fancy stuff
};
Drupal 7.x:
Drupal.behaviors.myModuleBehavior = {
attach: function (context, settings) {
$('input.myCustomBehavior', context).once('myCustomBehavior', function () {
// Apply the myCustomBehaviour effect to the elements only once.
});
}
};
@see: https://drupal.org/update/modules/6/7#jquery_once
Any function defined as a property of Drupal.behaviors will get called when the DOM has loaded. drupal.js has a $(document).ready() function which calls the Drupal.attachBehaviors() function, which in turn cycles through the Drupal.behaviors object calling every one of its properties, these all being functions declared by various modules as above, and passing in the document as the context.
The reason for doing it this way is that if your jQuery code makes AJAX calls which result in new DOM elements being added to the page, you might want your behaviors (e.g. hiding all h3 elements or whatever) to be attached to that new content as well. But since it didn't exist when the DOM was loaded and Drupal.attachBehaviors() ran it doesn't have any behaviors attached. With the above set-up, though, all you need to do is call Drupal.behaviors.myModuleBehavior(newcontext), where newcontext would be the new, AJAX-delivered content, thus ensuring that the behaviors don't get attached to the whole document all over again. There are full instructions on how to use this code on the Converting 5.x modules to 6.x or Converting 6.x modules to 7.x page.
This usage is not in fact exclusive to Drupal 6: the jstools package in Drupal 5 used this exact pattern to control the behaviors of its modules: collapsiblock, tabs, jscalendar, etc.
Drupal.behaviors practical example
The following is a more practical example. Drupal Behaviors are fired whenever attachBehaviors is called. The context variable that is passed in can often give you a better idea of what DOM element is being processed, but it is not a sure way to know if you are processing something again. Passing the context variable as the second argument to the jQuery selector is a good practice because then only the given context is searched and not the entire document. This becomes more important when attaching behaviors after an AJAX request. The following is an example of a Drupal.behavior that ensures that processing only happens once per DOM object.
Drupal.behaviors.myModuleBehavior = function (context) {
// This jQuery code ensures that this element
// is only processed once. It is basically saying:
// 1) Find all elements with this class, that do not
// have the processed class on it
// 2) Iterate through them
// 3) Add the processed class (so that it will not
// be processed again).
$('.module-class-object:not(.module-class-processed)', context).each(function () {
$(this).addClass('module-class-processed');
// Do things.
});
};
A real-live example is that in the OpenLayers module which uses this basic process to ensure that maps are only created once. It also utilizes Drupal behaviors to add parts and react to events.
Drupal 7.x:
Drupal.behaviors.myModuleBehavior = {
attach: function (context, settings) {
// This jQuery code ensures that this element
// is only processed once. It is basically saying:
// 1) Find all elements with this class, that do not
// have the processed class on it
// 2) Iterate through them
// 3) Add the myCustomBehavior-processed class (so that it will not
// be processed again).
$('input.myCustomBehavior', context).once('myCustomBehavior', function () {
// Apply the myCustomBehaviour effect to the elements only once.
});
}
};
Note: The above example of the Drupal 7 version is just a rewrite of the D6 example here presented and may not represent the current version of the OpenLayers module code.
Drupal.theme
Drupal.theme() is the client-side counterpart to the server-side theme() function. Here's what it looks like:
Drupal.theme = function (func) {
for (var i = 1, args = []; i < arguments.length; i++) {
args.push(arguments[i]);
}
return (Drupal.theme[func] || Drupal.theme.prototype[func]).apply(this, args);
};
So, when you make a call to Drupal.theme(), you pass in a function name as your first argument and all subsequent arguments will be arguments to be passed to that function. The function you pass in will need to be a prototype object of Drupal.theme(), an example of which is below:
Drupal.theme.prototype.myThemeFunction = function (left, top, width) {
var myDiv = '';
myDiv += '';
return myDiv;
};
And here's how you would call it:
Drupal.theme('myThemeFunction', 50, 100, 500);
Drupal.theme('myThemeFunction', 50, 100, 500); например вызов своей функции, ну и создание Drupal.theme.prototype.myThemeFunction = function (left, top, width) {}
Можно глобально объявить один объект, в качестве контейнера. И в него складывать все "глобальные" функции, он будет виден как глобально, так и в замыканиях.