Follow an event through the document
For an event that bubbles, dispatch travels through a capture phase toward the target and then a bubbling phase back through ancestors. This lets a parent handle actions from many descendant controls with one listener.
Clicking the span still finds its button through closest. A later button added to the same list can use the existing parent listener. The containment check keeps the delegated action inside its intended component boundary.
Observe phase order
Register one parent listener with capture:true and another ordinary listener. Add a listener on the button. For a basic click, expect parent capture, button target handling, then parent bubbling. Not every event bubbles; choose an appropriate event or explicit strategy for that case.
Stopping propagation is not cancelling behavior
stopPropagation prevents further propagation along the path. It does not automatically prevent link navigation or form submission. preventDefault requests cancellation of a cancelable default action. stopImmediatePropagation also stops later listeners on the same target; use these controls carefully because unrelated components may rely on the event.
Delegation tradeoffs
Delegation is useful for dynamic lists but does not eliminate the need for validation. A data attribute is client-controlled. Opening a lesson or deleting a server record must still follow the application's permission rules.
Practice
- Add a third button after listener registration and confirm delegation works.
- Click a list area outside a button; no lesson action should occur.
- Log eventPhase and currentTarget in capture and bubbling handlers.
- Explain why preventing navigation differs from stopping the click from reaching a parent.