Wednesday, February 13th, 2008

Sun.com Behaviour Registration Library

Category: JavaScript, Library

Greg Reimer has followed up and posted on the new event delegation library that he is using on Sun.com.

The library provides one object, reg which lets you hook behaviour via:

javascript

  1. reg.click('ul.foo > li > a.bar', myFunction);

What is happening

Once that bit of code runs, regardless of whether the entire DOM has finished loading into the browser, click events on elements matching ul.foo > li > a.bar will be handled by myFunction, which is passed a reference to the active element and the event object. This happens without any DOM traversal, and without any events ever being attached to any <a> elements. Even if the entire contents of document.body are subsequently overwritten by innerHTML, all those new element nodes implicitly inherit the correct behavior. No re-walking of the new DOM subtree ever occurs. No re-attachment of events ever occurs.

How is this even possible?

Two facts conspire to make this feasible. 1) The (document.body) is available almost immediately. 2) Most events bubble. All you need to do is to stand on document.body, and you’re privy to almost every event that occurs on the page, right out of the gate. No need to go seeking out the elements you need, they literally bubble their way to you. All you do is grab the event’s target and ask the question, does this element, or one of its ancestors, match ‘ul.foo > li > a.bar’? If so, run the associated function, if not, ignore it. This is really just event delegation, and it’s nothing new, but we’ve made little use of it on Sun.COM before now.

Posted by Dion Almaer at 6:52 am
2 Comments

+++--
3.5 rating from 17 votes

2 Comments »

Comments feed TrackBack URI

This is really awesome.

Comment by JustinMeyer — February 14, 2008

I think I’ve seen this before somewhere, but still: a logical and smart solution. Nice.

Comment by DiSiLLUSiON — February 19, 2008

Leave a comment

You must be logged in to post a comment.