javascript - What is DOM Event delegation? -


can please explain event delegation in javascript , how useful?

dom event delegation mechanism of responding ui-events via single common parent rather each child, through magic of event "bubbling" (aka event propagation).

when event triggered on element, the following occurs:

the event dispatched target eventtarget , event listeners found there triggered. bubbling events trigger additional event listeners found following eventtarget's parent chain upward, checking event listeners registered on each successive eventtarget. upward propagation continue , including document.

event bubbling provides foundation event delegation in browsers. can bind event handler single parent element, , handler executed whenever event occurs on of child nodes (and of children in turn). this event delegation. here's example of in practice:

<ul onclick="alert(event.type + '!')">     <li>one</li>     <li>two</li>     <li>three</li> </ul> 

with example if click on of child <li> nodes, see alert of "click!", though there no click handler bound <li> clicked on. if bound onclick="..." each <li> same effect.

so what's benefit?

imagine have need dynamically add new <li> items above list via dom manipulation:

var newli = document.createelement('li'); newli.innerhtml = 'four'; myul.appendchild(newli); 

without using event delegation have "rebind" "onclick" event handler new <li> element, in order act same way siblings. with event delegation don't need anything. add new <li> list , you're done.

this absolutely fantastic web apps event handlers bound many elements, new elements dynamically created and/or removed in dom. event delegation number of event bindings can drastically decreased moving them common parent element, , code dynamically creates new elements on fly can decoupled logic of binding event handlers.

another benefit event delegation total memory footprint used event listeners goes down (since number of event bindings go down). may not make of difference small pages unload (i.e. user's navigate different pages often). long-lived applications can significant. there difficult-to-track-down situations when elements removed dom still claim memory (i.e. leak), , leaked memory tied event binding. event delegation you're free destroy child elements without risk of forgetting "unbind" event listeners (since listener on ancestor). these types of memory leaks can contained (if not eliminated, freaking hard sometimes. ie i'm looking @ you).

here better concrete code examples of event delegation:


Comments

Popular posts from this blog

java - How to specify maven bin in eclipse maven plugin? -

single sign on - Logging into Plone site with credentials passed through HTTP -

php - Why does AJAX not process login form? -