Join Now! It's FREE. Get full access and benefit from this site
Wednesday, 10 March 2010 11:03
In jQuery 1.3, the team introduced the live() method, which allows us to bind event handlers to elements on the page, as well as any that might be created in the future dynamically. Though not perfect, it definitely proved to be helpful. Most notably, live() bubbles all the way up, and attaches the handler to the document. It also ceases to work well when chaining method calls, unfortunately. Delegate() was introduced in version 1.4, which almost does the same thing, but more efficiently.
We’ll examine the more specific differences between the two methods in today’s video quick tip. Thanks to the FireQuery Firebug extension, we’ll have the tools to more easily understand the differences between the two.
// Bind attaches an event handler only to the elements
// that match a particular selector. This, expectedly,
// excludes any dynamically generated elements.
$('#items li').click(function() {
$(this).parent().append('<li>New Element</li>');
});
// Live(), introduced in 1.3, allows for the binding
// of event handlers to all elements that match a
// selector, including those created in the future.
// It does this by attaching the handler to the document.
// Unfortunately, it doesn't work well with chaining.
// Don't expect to chain live() after calls like
// children().next()...etc.
$('li').live('click', function() {
$(this).parent().append('<li>New Element</li>');
});
// Delegate, new to version 1.4, perhaps should have been a complete
// replacement for Live(). However, that obviously
// would have broken a lot of code! Nonetheless,
// delegate remedies many of the short-comings
// found in live(). It attaches the event handler
// directly to the context, rather than the document.
// It also doesn't suffer from the chaining issues
// that live does.
$('#items').delegate('li', 'click', function() {
$(this).parent().append('<li>New Element</li>');
});
// By passing a dom element as the context of our selector, we can make
// Live() behave (almost) the same was that delegate()
// does. It attaches the handler to the context, not
// the document - which is the default context.
// The code below is equivalent to the delegate() version
// shown above.
$('li', $('#items')[0]).live('click', function() {
$(this).parent().append('<li>New Element</li>');
});
This can definitely be a confusing topic. Please feel free to ask questions, or discuss within the comments. Thanks so much to Elijah Manor for clarifying a few things for me on this topic!