What are Drupal behaviours at all?
What type of service layer it offers to module developers?
What type of relation it maps to jQuery.ready function?
views:
129answers:
2Long version: Drupal.behaviors is not simply a replacement for jQuery.ready since the latter only runs once (when DOM is ready for manipulation): behaviors can be fired multiple times during page execution and can be run whenever new DOM elements are inserted into the document.
Also, modules could override or extend an existing behavior (e.g. if one module has a behavior of adding a bounce effect on all links, a second module could replace the behavior by a different bounce effect).
Short version: it's more modular, though the documentation could be improved.
Also, starting in Drupal 7, settings defined using drupal_add_js (PHP) or in Drupal.settings.modulename (Javascript) are directly passed as second parameter (the first one being the context) to the behavior.
For example:
Drupal.behaviors.changeLinks = function(context, settings){
if (!settings) settings = Drupal.settings.changeLinks;
$("a", context).hover(function() {
$(this).css('color', settings.color);
});
};
And if one of your script (or another) creates new nodes, it could still have the behaviors applied to the new nodes without having to know what other modules are iinstalled:
var newNodes = $('<a href="#">Hello</a> <a href="#">World</a>').appendTo('#someDiv');
Drupal.attachBehaviors(newNodes);
You might find these links useful
- http://drupal.org/node/205296
- (Nice one) http://www.switchonthecode.com/tutorials/drupal-6-basic-javascript-w-jquery
If you don't mind paying $5 for a 13 minute video check out http://buildamodule.com/drupal-video/understanding-drupal-javascript-behaviors-video (Note: I don't have any connection to these guys and cannot vouch for the video. The preview seems decent though)