corroded
corroded

Reputation: 21604

should i convert all my live functions to delegates?

Based on my question here: adding .live to click functions in jquery

It seems that the general consensus is that delegate > live in performance purposes. Should I be converting all my lives to delegates? If so, why use the live function at all since delegate is performance wise better?

And does delegate "ignore" everything when it doesn't see my selector in the DOM?

Upvotes: 0

Views: 357

Answers (2)

David Tang
David Tang

Reputation: 93714

You shouldn't refactor your code for performance if there aren't any visible problems. However, there are other issues with live() that may affect maintainability of your code:

  • Live doesn't work with stopPropagation().
  • Live is like a global variable. Different instances of a class may interfere with each other if using live().

As for why live() still exists - according to this article:

As a general best practice, never use .live in your applications. After live was introduced in jQuery, Justin argued the need for better a event delegation API, and delegate was created. The main reason jQuery still supports live is for legacy code.

Finally, delegate() works exactly like live(), except that it attaches the event handler to an element you specify, whereas live() attaches it to document. When events bubble up to the specified element, it ignores the event if it didn't originated from, or pass through, an element that matches the given selector.

Upvotes: 4

Jarrett Widman
Jarrett Widman

Reputation: 6439

.live() would also ignore anything if it doesn't find the selector in the DOM. See how they are equivalent from the jQuery docs http://api.jquery.com/delegate/:

Delegate is an alternative to using the .live() method, allowing for each binding of event delegation to specific DOM elements. For example the following delegate code:

$("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");
    });
});

Upvotes: 0

Related Questions