Wednesday 14 December 2011

jQuery 1.7 Event Delegation.. Gitanes and whisling at girls are they walk by

In the wonderful world of JS event listeners cost memory.
Lots and lots of memory!
In today's shiney shiney click,drag swipe an pinch world has a whole heap of event listeners floating around smoking cheap ciggarettes, whistling at the girls and generally making your web site perform badly. But all is not lost jQuery provides some really easy methods for handling event listeners efficiently through the wonders of event delegation.

In a bit of an extreme example but hey we are Domino Developers we are extreme! Imagine a situation where a 10×10 cell table needs to have an event listener on each cell; let’s say that clicking on a cell adds or removes a class that defines the cell’s background color. A typical way that this might be written:


$('table').find('td').click(function() {
    $(this).toggleClass('yuckygreen');
});

Enter jQuery 1.7's  on() method. It acts as a utility that wraps all of jQuery’s event listeners into one convenient method, and the way you write it determines how it behaves.  so we replace .click()  .on() using this code.

$('table').find('td').on('click',function() {
    $(this).toggleClass('active');
});

Is that cool or what? Mind you we are still binding 100 hundred event listeners to our page, one to each individual table cell and they are still puffing away on their Gitanes and scratching their arses in a most undignified and memory wasting way . Since the majority of events bubble up the DOM tree, we can bind a single event listener to one element (in this case, the <table>) and wait for events to bubble up from its children. Like this

$('table').on('click','td',function() {
    $(this).toggleClass('active');
});

All we’ve done is moved the td selector to an argument inside the .on() method. Providing a selector to .on() switches it into delegation mode, and the event is only fired for descendants of the bound element (table) that match the selector (td). With that one simple change, we’ve gone from having to bind one hundred event listeners to just one. You might think that the browser having to do one hundred times less work would be a good thing and you’d be completely right as I found this evening!

[If you are using a version of jQuery less than 1.7 all is not lost.. look up the .delegate() method and you will be able to do nearly the same thing!]

Disqus for Domi-No-Yes-Maybe