What is the difference between .delegate () and live ()?

As

$("table").delegate("td", "hover", function(){ $(this).toggleClass("hover"); }); 

It 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 not the same to write

 $("table td").live('hover', function() {}); 

So what is .delegate() for?

+6
jquery events delegates
source share
3 answers

.live() listens on document , where .delegate() listens on a more local element, <table> in this case.

Both of them act the same way, listening to the events bubbling up, and one before .delegate() just bubbling less than being caught.

Your example:

 $("table td").live('hover', function() {}); 

Not the same as it attaches the event handler to document again, and not to <table> , therefore .delegate() for more local elements, more efficient in most cases ... although it still uses .live() under covers.


Also keep in mind that $(selector) retrieves items, so $("table td") selects a bunch of items for real no good reason when using .live() , where as $("table").delegate() selects only <table> elements, therefore even initially it is more efficient without starting the selector and discarding the result.

+4
source share

The live() method is to place the handler at the top level of the DOM (document), which detects when the selected event bubbles up to that level (and then checks to see if it was selected by an element that matches your selector).

delegate() works the same way, but a handler is placed on your selected element (so that it can only detect events passed by the descendants of this element).

The disadvantages of live() are 1) the performance problems inherent in detecting and checking all events that bubble at the document level, and 2) the fact that you cannot stop distributing at all these events (since you won, I don’t know about them until they not reached document level).

delegate() mitigates both of these problems by allowing you to limit the handler to a smaller set of elements (elements that match your selector and their descendants) rather than the whole page.

+5
source share

Document:

Since the .live () method handles events when they propagate at the top of the document, it is not possible to stop the distribution of live events. Similarly, events handled by .delegate () will always be passed to the element to which they are delegated; event handlers on any elements below it will already be executed by the time the delegated event handler is called.

0
source share

All Articles