Last updated October 22, 2012. Created by katbailey on September 5, 2008.
Edited by neilt17, RandallKent, TravisCarden, zzolo. 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 initialised therein.
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 how your module is configured, for example, or you may want to simply let JavaScript know what the base path is. You just create a PHP array of settings, as follows:
<?php
$my_settings = array(
'basepath' => $base_path,
'animation_effect' => variable_get('effect', 'none')
);
?>Then call drupal_add_js() and pass in this array, with "setting" as your second parameter:
<?php
drupal_add_js(array('my_module' => $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.my_module.basepath;
var effect = Drupal.settings.my_module.animation_effect;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
};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 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.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 = '<div id="myDiv" style="left:'+ left +'px; top:'+ top +'px; width:'+ width +'px;">';
myDiv += '</div>';
return myDiv;
};And here's how you would call it:
Drupal.theme('myThemeFunction', 50, 100, 500);See here for the official documentation on this.
Drupal.locale
The Drupal.locale property works in conjunction with Drupal.t, the JavaScript equivalent of the server-side t() function. It holds a collection of string translations so that Drupal.t can then access the required string from Drupal.locale in order to translate what was passed into it.
Further information:
- See the JavaScript, jQuery and AJAX section in the handbook, with code snippets, etc.
- PHP JavaScript functions as documented on api.drupal.org.
- #ahah attribute in the FAPI documentation.
- Check the various JavaScript enhancement in D6:
- AJAX with 6.x FormAPI: some notes about creating AJAX calls in D6.
- #DANGEROUS_SKIP_CHECK removed. Ahah can be used instead.
- JavaScript behaviors. Behaviors are event-triggered actions that attach to page elements, enhancing default non-JavaScript UIs..
- JavaScript themeing.
- Translation of JavaScript files.
- JavaScript aggregation and compression.
Comments
The way in which
The way in which Drupal.behaviors works to trigger a document ready event didn't work in Drupal 7 for me:
Drupal.behaviors.myModuleBehavior = function (context) {//do some fancy stuff
};
I had to implement it as such:
Drupal.behaviors.myModuleBehavior = {attach: function (context, settings) {
//do some fancy stuff
}
};
www.jonbrace.co.uk
behaviors
Hello,
I'm trying to make javascript with drupal but it's remaining one thing that i don't understand. It's the js object behaviors. I understood how implement it but i don't understand the goal of it. Please, is there somebody can explain it me ?
Thanks,
Fab.
behaviors
i'm answering me, it could be helpful for people like me; the main advantage of using Drupal behaviors is that they are re-attachable, which becomes very useful when utilising AHAH/AJAX. Using '$(document).ready()' within 'script.js' means it will run only once (once the DOM is ready) each page load, whereas behaviors will be attached each time 'Drupal.attachBehaviors()' is called (and in Drupal 6 the 'drupal.js' file (/misc/drupal.js) is already set up to attach all behaviors for us upon intital page load).
Object declared to be equal to itself?
In the first example, why is the
DrupalObject being declared equal to itself?Why could you not just use
var Drupal = { 'settings': {}, 'behaviors': {}, 'themes': {}, 'locale': {} };?