Hacker News new | comments | show | ask | jobs | submit login

Isn't live really used in instances where an element is being added to the DOM after the page has loaded? with delegate, it is attempting to check an event click on an element which does not exist in the DOM.

I'm far from a Javascript expert, but it seems to me that .live is just so much easier to understand conceptually. jQuery is always looking at the DOM.




No, live and delegate are mostly interchangeable (for reasons explained in the article). They are both used generally to attach a handler to a DOM element indirectly, by actually attaching it to one of the ancestor elements, and then listening for events that propagate up to that ancestor element, and then checking to see if the target of the event matches the target supplied in the live or delegate method as an argument.

The two reasons for using either one are either:

a) to attach handlers to DOM elements that may not yet exist in the DOM.

b) to attach a handler to a single element or small group of elements, listening for events on descendent elements, instead of looping through and attaching the same function to 100 individual elements in the DOM.

For the most part, live is now generally discouraged in favor of delegate (also for reasons explained in the article). In fact, here is the description for .delegate() from the jQuery docs:

    Delegate is an alternative to using the .live() method, allowing
    for each binding of event delegation to specific DOM elements.


this is especially useful with AJAX since the DOM elements may get replaced.




Applications are open for YC Summer 2018

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact

Search: