Since
$("table").delegate("td", "hover", function(){
$(this).toggleClass("hover");
});
Is equivalent to the following code written using .live():
$("table").each(function(){
$("td", this).live("hover", function(){
$(this).toggleClass("hover");
});
});
according to jQuery API.
I bet I'm wrong but isn't it the same of writing
$("table td").live('hover', function() {});
So, what's is .delegate()
for?
The bind() method will not attach events to those elements which are added after DOM is loaded while live() and delegate() methods attach events to the future elements also. The difference between live() and delegate() methods is live() function will not work in chaining.
The delegate() method attaches one or more event handlers for specified elements that are children of selected elements, and specifies a function to run when the events occur. Event handlers attached using the delegate() method will work for both current and FUTURE elements (like a new element created by a script).
The way live()
works is that it places a handler on the top level of the DOM (the document) that detects when your chosen event bubbles up to that level (and then checks to see if it was thrown by an element that matches your selector).
delegate()
works the same way, but the handler is placed on your selected element (so it can only detect events thrown by descendants of that element).
The downsides of live()
are 1) the performance issues inherent in detecting and checking all events that bubble to the document level, and 2) the fact that you can't stop propagation at all on those events (since you won't know about them until they reach the document level).
delegate()
mitigates both of those issues by letting you constrain the handler to a smaller set of elements (the elements that match your selector and their descendants) rather then the whole page.
.live()
listens on document
where as .delegate()
listens on a more local element, the <table>
in that case.
They both act the same listening for the events to bubble, the one to .delegate()
just bubbles less before being caught.
Your example of:
$("table td").live('hover', function() {});
Isn't the same, as it again attaches an event handler to document
and not the <table>
, so .delegate()
is for more local elements, more efficient in most respects...though it still uses .live()
under the covers.
Also keep in mind that $(selector)
retrieves the elements, so $("table td")
selects a bunch of elements really for no good reason when using .live()
, where as $("table").delegate()
selects only the <table>
elements, so even initially it's more efficient by not running the selector and discarding the result.
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