[development] behaviors context

Henrique Recidive recidive at gmail.com
Fri May 29 20:13:39 UTC 2009


2009/5/29 David Cohen <drupal at dave-cohen.com>:
> So just to clarify, will the context always refer to a single element?
> In other words should my code be:
>
> $elem = $(context).get(0);
> do_my_behavior($elem);
>
> or, more like:
>
> $(context).each(function () {
>  $elem = $(this).get(0);
>  do_my_behavior($elem);
> });

It should be more like this:

Drupal.behaviors.myBehavior = function(context) {
  $(context).each(function () {
    // 'this' is a DOM Element.
    do_my_behavior(this);
  });
};

or you can include your selector and use context as it is supposed to be used:

Drupal.behaviors.myBehavior = function(context) {
  $('.my-behavior-class:not(.my-behavior-processed)',
context).each(function () {
    // 'this' is a DOM Element.
    do_my_behavior(this);
    $(this).addClass('my-behavior-processed');
  });
};


Henrique

>
>
> And in the first invocation, when context == document, will
> $(document).get(0) return the document?
>
> Thanks everyone for helping me understand.
>
> -Dave
>
>
> On Fri, 29 May 2009 11:44 -0700, "Earl Miles" <merlin at logrus.com> wrote:
>> I totally disagree. It's either a jquery object or something you can
>> easily make into a jquery object. Using $(context) should always work
>> and you can get a DOM element using $(context).get(0). Ignoring context
>> will lead to poor performance.
>


More information about the development mailing list