Skip to content

Instantly share code, notes, and snippets.

@Raynos
Created March 24, 2014 00:41
Show Gist options
  • Save Raynos/9732226 to your computer and use it in GitHub Desktop.
Save Raynos/9732226 to your computer and use it in GitHub Desktop.

events

Doing it raw

You just add an event listener to your element

elem.addEventListener(eventType, listener)

Using event delegation

You tell the delegator to queue an event listener for the (elem, eventType) tuple.

var delegator = Delegator(document.body)

delegator.addEventListener(elem, eventType, listener)

The delegator adds a single global listener and figures out which listeners to dispatch it to. basically it checks whether the (ev.target, ev.type) has any listeners attached to it.

If the (ev.target, ev.type) has no listeners it tries (ev.target.parentNode, ev.type) recursively until it hits the root node of the delegator (in this case document.body)

Advantages of event delegation

The advantages of the event delegation technique is that there is only a single listener per event and we have our own dispatching logic.

We avoid the entire bubbling phase and we reduce the number of listeners in the DOM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment