jquery.eventdelegationIn standard event handling an event handler is bound to each selected element one-at-a-time. The following list of links is an example. Though the code is concise (gotta love jQuery), jQuery is binding the handler to each item individually behind-the-scenes.
What happens when you load new content into the list? Nothing. That's because event handlers are bound only once. If you want additional links to behave as the original links, event handlers need to be rebound manually.
$('#x01 li').click(function () {
$(this).toggleClass('highlight');
return false;
});
$('.linkRebinder').click(function () {
$(this).prev().find('li').unbind('click').click(function () {
$(this).toggleClass('highlight');
return false;
});
});
Event delegation solves the problem above. With event delegation, you bind your handler only once to the parent element containing all the children meant to have handlers. In this example, we bind our event to the unordered list, instead of the list items.
Whenever an additional item is added, it automatically "inherits" the event handler. That's the major benefit of event delegation: bind-once event handling. Another benefit is that this method is significantly faster on-bind, since the handler is bound to just one element.
$('#x02 ul').click(function (e) {
if ($(e.target).parent().parent().is('li'))
$(e.target).parent().parent().toggleClass('highlight');
return false;
});
The event delegation method does require some additional planning and setup. Fortunately, there is a jQuery plugin that handles the details for us. jQuery Listen provides an elegant interface to programming event delegation handlers.
The downside of jQuery Listen is that it requires you to specify the innermost element that could receive the event. In our example, the event handler must listen on li a span, instead of just li as in the previous examples. Internally, jQuery Listen detects the actualy click target, which is always the innermost element. In most situations, this requires careful planning.
jQuery Listen also requires you to explicitly call preventDefault() if you want to stop the default event handler. This may be awkward for anyone working with standard jQuery event handlers, where you simply return false from your handler function to prevent the default action.
$('#x03 ul').listen('click', 'li a span', function (e) {
$(this).parent().parent().toggleClass('highlight');
e.preventDefault();
});
jquery.eventdelegationI created the jquery.eventdelegation plugin to solve the problems associated with jQuery Listen. jquery.eventdelegation allows arbitary element selectors, so you don't have to worry about the innermost element. And as an extra bonus, you can cancel the default handler just by returning false from your handler function, the same way you would with a standard handler.
$('#x04 ul').delegate('click', 'li', function () {
$(this).toggleClass('highlight');
return false;
});