← Back to Engine

Advanced Event Handling & Delegation


Events traverse the DOM tree in a 3-phase propagation sequence defined by the W3C DOM specification.

1. The 3 Event Propagation Phases

  1. Capturing Phase (Trickle Down): Event propagates down from Window -> Document -> Body down to the target node parent.
  2. Target Phase: Event triggers on the actual clicked node (e.target).
  3. Bubbling Phase (Bubble Up): Event travels back upwards to ancestor nodes.

2. Event Delegation Pattern

Instead of binding 1,000 separate event listeners to dynamic list items, attach 1 single listener to the parent container. Use e.target.closest(selector) during the bubbling phase to match child triggers efficiently!

3. Event Control Utilities

  • e.preventDefault(): Cancels default browser behavior (e.g. form submit, link navigation).
  • e.stopPropagation(): Stops the event from bubbling up to parent listeners.
  • e.stopImmediatePropagation(): Prevents other listeners on the same element from executing.

The Challenge: Event Delegator Utility

Implement setupEventDelegation(parentContainer, selector, callback) that listens for click events on parentContainer, checks if the clicked element matches selector using e.target.closest(selector), and invokes callback passing its data-id attribute.