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

Delegated events let you handle events for child elements that aren't even in the DOM at the time you attach the handler. The jQuery docs explain it:

api.jquery.com/on/#direct-and-delegated-events

> Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready. ... In addition to their ability to handle events on descendant elements not yet created, another advantage of delegated events is their potential for much lower overhead when many elements must be monitored.




Event delegation is entirely different to how you would normally do it. It relies on the events from the inner elements bubbling up through the parent elements. So you put an event listener on some common ancestor (the tbody in this case) to the elements you care about (the tr elements). A click event on some tr will bubble up to the tbody*, the event handler there can check whether the originating element matches the selector "tr", and if it does, it does something like: `yourCallback.call(event.srcElement, event)`.

The obvious benefit of this is that if there are 10,000 tr elements, it is quicker to attach your listeners (there's only a single listener on the tbody) and less memory is consumed (again, only a single listener). A more subtle set of benefits come from manipulation of the DOM. Your listener is able to respond to events on elements that have been inserted after the listener was first registered. Also, when removing tr elements from the DOM you don't have to remember to unbind all your event handlers (a common source of memory leaks, as they can be GC'd)




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

Search: