Sunday, February 13, 2011

The Difference Between jQuery’s .bind(), .live(), and .delegate()

The difference between .bind(), .live(), and .delegate() is not always apparent. Having a clear understanding of all the differences, though, will help us write more concise code and prevent bugs from popping up in our interactive applications.

.bind()


$('a').bind('click', function() { alert("That tickles!") });
This is the most straight forward binding method. jQuery scans the document for all $('a') elements and binds the alert function to each of their click events.

.live()


$('a').live('click', function() { alert("That tickles!") });
jQuery binds the alert function to the $(document) element, along with 'click' and 'a' as parameters. Any time an event bubbles up to the document node, it checks to see if the event was a click and if the target element of that event matches the 'a' CSS selector. If both are true, the function executes.
The live method can also be bound to a specific element (or “context”) other than document, like this:

$('a', $('#container')[0]).live(...);

.delegate()


$('#container').delegate('a', 'click', function() { alert("That tickles!") });
jQuery scans the document for $('#container'), and binds the alert function along with the click event and 'a' CSS selector as parameters. Any time an event bubbles up to $('#container'), it checks to see if the event was a click and if the target element of that event matches the CSS selector. If both checks are true, it executes the function.
Notice this is similar to .live(), except that it binds the handler to the specified element instead of the document root. The astute JS’er might conclude that $('a').live() == $(document).delegate('a'), right? Well, no, not exactly.

http://www.alfajango.com/blog/the-difference-between-jquerys-bind-live-and-delegate/?utm_content=backtype-tweetcount&utm_medium=bt.io-twitter&utm_source=netvibes.com

No comments: