Oct 13, 2010
Introducing jQuery’s Delegate Method

Optimizing and refactoring jQuery code is not as difficult as it seems. You do need to be aware of the most currently available methods though, so below we’ll examine the new to 1.4.2 method .delegate().
// Bad Code
$('#menu li a').click(function() {
$(this).hide();
});
// Good Code
$("#menu li a").live('click', function() {
$(this).hide();
});
// Coding Way Forward
$("#menu").delegate('li a', 'click', function() {
$(this).hide();
});
This technique will offer substancial boosts in performance when used appropriately. In previous versions of jQuery .live() and .delegate() where not available. During that time the typical way of approaching the event listener for clicking was through .click(). However, with the introduction of these two new methods we can use to achieve the same effect with less strain on the DOM.
In the first example .click added an event handler to all anchors in links in the element corresponding with the ID of menu (#menu). Using this method every selected element gets its own event handler. It bound the click to a callback defined as an inline function, $(this).hide(); This is ok, if you have one link, but if you have two it become redundant.
In the second example .live(), the effect is the same but it uses only one handler. It uses the parent element of the jQuery selector. So even if there 100 child li a’s of #menu, it still only uses one event handler.
The .delegate() improves on this by choosing the parent as explicitly defined, instead of relying on the DOM to calculate which element that is. It then applies a single event handler to that element. The only time .live() is appropriate is when the parent element is dynamic, meaning it’s not always the same for the children you want to target. Otherwise, using .delegate() will significantly decrease the use of the DOM when dealing with a large number of elements.
