When should I use behaviors? Can I attach them to any DOM node?
The attach function of all registered behaviors (all properties of the Drupal.behaviors object) will be invoked when behavior should be added to elements, either when the DOM is ready (ie. page load) and when elements are added to the DOM. The detach function will be called when behaviors should be detached from elements: just before elements are removed from the DOM, moved in the DOM or a form is submitted. The context parameter will always be a parent of the added/removed/moved/submitted elements, the single added/removed/moved/submitted element itself or the whole document element. The settings parameters will be the settings for the context, usually the Drupal.settings object as set by calls to drupal_add_js() from PHP. For detach, the trigger parameter will contains the kind of event that triggered the call: 'unload' (elements removed), 'move' (elements moved) or 'serialize' (form is being submitted).

The attach (and detach) functions of a behavior can be used multiple time over the same portion of the DOM tree. So the same element could be processed multiple time by the same code. It is up to the code itself to avoid processing (ie. binding event handlers, altering CSS styles, etc.) multiple times for the same elements. The easiest solution for this is to use the jQuery Once plugin (which is provided by Drupal 7) like this:

$(selector).once('behavior-name').doSomething();
$(selector).once('behavior-name', function(){ /*do something*/ });


Since a behavior is being attached/detached to/from a context, the context object can be used to restrict your jQuery queries to only the affected element or DOM subtree, like this:

$(selector, context).doSomething();


Putting all this together means the base pattern to process and add behaviors to elements on the page should looks like this:

(function($) {
  Drupal.behaviors.doSomething = {
    attach: function(context, settings) {
      $('div.something', context).once('do-something').doSomething({
        param1: settings.something.param,
        param2: 'something else'
      });
    }
  }
})(jQuery);


You can manipulate thhe Drupal.behaviors object tree, but be careful to avoid breaking other behaviors. I common usage is to use your behavior object (ie. Drupal.behaviors.myBehavior) to store information extracted from the elements during attach and consumed by event handlers.

If you write code that dynamically add or remove elements to the DOM, you should invoke Drupal.attachBehaviors or Drupal.detachBehavior on the (closet) parent element of the added/removed elements.