Monday, March 7, 2016

Event Delegation, Propogation, Capturing and Bubbling

Monday, March 7th, 2016

Event delegation is the HTML mechanism that allows developers to setup event handlers for nodes, which are fired whenever a child of that node, through bubbling, triggers that event handler. In other words, children inherit the event handlers of their parents and, when the child is selected, fire each one of it's parents event handlers.


Example:
<ul onclick = 'alert('yo!')'>
      <li> One </li>
      <li> Two </li>
      <li> Three </li>
</ul>
- When any of children of the <ul> element are clicked on, the event handler 'onclick' fires, despite 'onclick' being assigned to the <ul> element and not any of the <li> elements.

So why use bubbling? Bubbling is useful to make code more readable and easier to manipulate. Instead of having to assign each one the <li> elements to the 'onclick' event handler, we instead can simply assign the parent element the event handler which will then fire when any of the children are selected.

Misconstrued: Sometimes
Often, event bubbling is synonymous with event propagation but they are different. Event propagation encompasses capturing and bubbling, though due to the deprecation of event capturing, event bubbling and propagation have inadvertently become synonymous.

Sources:
http://www.javascripter.net/faq/eventbubbling.htm
https://learn.jquery.com/events/event-delegation/
http://stackoverflow.com/questions/4616694/what-is-event-bubbling-and-capturing
http://stackoverflow.com/questions/1687296/what-is-dom-event-delegation

No comments:

Post a Comment