views:

129

answers:

2
+7  Q: 

Drupal behaviours

  • 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?

+11  A: 

Long 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);
wildpeaks
+3  A: 

You might find these links useful

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)

Sid NoParrots