I read in another question that you'd use live if there wasn't a container to attach the event to with $.delegate that you knew wasn't going away, but why not simply do:
$('body').delegate('.myThing', 'click', function() { ... });
I've become fairly convinced that there's no reason to use $.live()
in any new code and that its only still here for backwards compatibility.
Of course, I'm often wrong. So I'm asking: When would I use $.live instead of $.delegate and why?
$.live()
...is slightly more concise if you don't need to use a specific element for the context.
$.delegate()
...is slightly more convenient if you already have a context selected, especially if you're chaining to perform other operations on that context.
...is slightly more efficient, provided you're not performing any other operations on the target elements, in that it doesn't needlessly evaluate the target selector during binding.
...allows you to target multiple contexts, which live() does not (though see implementation note below).
Otherwise, it's a matter of personal preference. You can accomplish the same things with both methods - indeed, the current (as of 1.4.2) implementation of delegate
merely delegates to live
!
delegate: function( selector, types, data, fn ) {
return this.live( types, data, fn, selector );
}
Even though you could effectively use the current implementation of live() as a substitute for all forms of delegate(), you should avoid calling live() the way delegate() calls it - the undocumented fourth parameter is intended for internal use only. Normally, you would provide a context for live() the way you would provide a context to any jQuery selector - by passing the element as the second parameter to $():
$(selector, contextElem).live(...);
If you need to use a selector for the context (as in a scenario where you wish to bind delegated events to multiple, separate context elements) you should stick to using delegate():
$("body>div").delegate(selector, ...);
// all of these are the same - pick the shortest form that fits your needs:
$(document).delegate('.myThing', 'click', function() { ... });
$('.myThing', document).live('click', function() { ... });
$('.myThing').live('click', function() { ... });
// this should only be done using delegate
$("#myTable, #myDiv, #myMarquee").delegate('.myThing', 'click', function(){...});
The .delegate() function was added in 1.4.2. I have no reason to use .live() anymore either. It's just a matter of breaking old habits. The .delegate() function does the same thing in a different and much more efficient way.
Here is a great article on .delegate(): http://www.learningjquery.com/2010/03/using-delegate-and-undelegate-in-jquery-1-4-2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With