The other issue with using context is that it is unreliable for a second reason: behaviors may actually misbehave when focusing on only a small portion of the DOM. Example: context contains several rows of a table, and you are adding odd/even classes to a table in a behavior. If a behavior is fed just the modified rows, this may lead to unexpected behavior (Reason: there may be other rows not fed into the context, thus throwing off odd/even counts).
That's a basic example. In the JS book I wrote, I provided a more elaborate examples of contexts causing problems. And there are still others -- like cases where AHAH content has its own JS which may modify your DOM further. But the basic principle is the same: Assuming that the attachBehaviors call is passing you what you need is not a good assumption. And since attachBehaviors can be called from anywhere (not just in AHAH/AJAX callbacks) and for any reason, it's dangerous to presume you know what you're getting. re: performance... in most cases you are talking a negligible difference. DOM optimization in mainstream browsers is good enough that a search through an entire document is almost always "fast enough". Shaving 10 msecs off of that time isn't going to make much of a difference (assuming you could actually shave that much from the search time). There are two patterns in Drupal JS to "prevent" the same behavior from processing the same data twice. One is the :not(processed-X) pattern, which seems to be pretty reliable, and is pretty much entirely in the hands of the author of the behavior (barring a misanthrope who decides to remove your processed classes). The other is the context, which requires that both the caller of attachBehavior() and the behavior have the same set of assumptions about what is being passed in and what needs operating on. This is not always the case, and there are easy-to-reproduce gotchas (like zebra striping, AHAH'd JavaScript that alters the DOM, and so on). Matt On Fri, May 29, 2009 at 1:44 PM, Earl Miles <[email protected]> wrote: > Matt wrote: >> >> Thus my original claim: You are at the mercy of whatever calls >> Drupal.attachBehaviors(). Unless you are absolutely positive you can >> account for all use cases (and thus all callings of Drupal.attach()), >> you're better off ignoring context. > > 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. > -- http://technosophos.com http://querypath.org
