Study guides · Advanced

Trace event paths and propagation

Follow capture, target, and bubble along a tree, distinguishing target, currentTarget, listener order, and handlers that a stop flag prevents from being reached.

Ask Logeia about this articleTry the three questionsReview your answers

Updated

On this page
  1. Goal: observe one click from several places
  2. Construct the path and select registered listeners
  3. target stays fixed while currentTarget changes
  4. Stopping propagation differs from stopping every local listener
  5. Implementation: log dispatch target and current registration separately
  6. Failure: phase and stop settings make an update unreachable
  7. Exercise: repair stopping and mutation targets independently
  8. Ask Logeia about this articleCheck your understanding

Goal: observe one click from several places

A button click can invoke a handler on the button and another on a parent panel. The event is not necessarily recreated independently at every node: dispatch visits several listeners along an event path. This lesson follows a bubbling click through an ordinary tree and asks which listener runs during capture, at the target, and during bubbling. The prerequisites are DOM parent–child relationships and function calls. The goal is to explain a visible update using three separate identities: the dispatch target, the listener that ran, and the node that listener changed.

The teaching model excludes Shadow DOM, default actions, native UI behavior, and nested synchronous dispatch from inside a listener. Naming an event click does not mean that every event type follows identical bubbling rules; the lesson fixes a bubbling click as its input. In the DOM and events model, change the tree, listener registrations, and dispatch target independently. At each step compare the path with the currently executing registration rather than treating every highlighted element as a new target.

Construct the path and select registered listeners

Assume root contains panel, which contains button. For a click on button, the inward traversal visits root, panel, then button, while the outward traversal visits button, panel, then root. The capture option determines which registered listeners are selected during each visit. Listeners on the target are handled at the target phase, with capture registrations distinguished from non-capture registrations. Walking the tree twice and invoking every listener on both walks would therefore be incorrect.

Registration order matters when several listeners apply at the same invocation position. One can mutate shared state that the next reads. Keep the model’s registration order fixed rather than sorting listeners differently on every run. Also distinguish a path prepared for dispatch from the listener currently executing on that path. Doing so reveals the boundary between dispatch machinery and application code. A handler that changes a label does not itself explain how the engine selected that handler; the path and registration settings provide that cause.

target stays fixed while currentTarget changes

In this ordinary-tree example, target remains button. A root listener sees currentTarget as root; a panel listener sees it as panel. This distinction matters for event delegation, where a parent registration handles events from several descendants. Assigning textContent to currentTarget may replace the entire panel when the intended update concerned a child label. The original target and the current registration can coincide, but they must not be represented as one unconditional field.

InvocationPhasetargetcurrentTarget
root capturecapturebuttonroot
panel capturecapturebuttonpanel
button non-capturetargetbuttonbutton
panel non-capturebubblebuttonpanel
root non-capturebubblebuttonroot

Stopping propagation differs from stopping every local listener

stopPropagation prevents progress along later parts of the path. It differs from stopImmediatePropagation, which also prevents later listeners in the current invocation from running. A capture listener on panel can stop dispatch before button is reached, so the button’s update never executes. The event did occur; the important question is where the stop flag became set. This model supports stopPropagation and displays that scope. Do not infer that every missing handler means no event was generated.

Preventing a default action is another separate operation. Cancelling a link’s navigation and preventing propagation to a parent registration are different decisions. Because default actions are outside this model, adding a stop flag does not simulate the success or failure of real navigation. Shadow boundaries also introduce additional rules for paths and visible targets. The fixed target observed in this ordinary-tree exercise is a declared assumption, not a universal statement about every possible document and observer.

Implementation: log dispatch target and current registration separately

The independent program below schedules registered listeners along a fixed path. It is not a complete implementation of dispatchEvent; it tests order and the two target fields for this restricted tree. Its output is root → panel → button → panel → root. Every saved target remains button, while currentTarget changes. Inspecting the trace explains why a listener ran instead of relying only on its eventual text output.

When adding a stop flag, distinguish stopping the outer path traversal from skipping or terminating the inner list of listeners. A return in the wrong loop can stop a different scope from the one intended. Test both shared-state updates and a handler that is never reached. Recording why an eligible-looking listener did not run helps identify a missing update. The sequence should be derived from the input registrations and path, not written as a fixed answer that happens to match the default example.

javascript
const path = ['root', 'panel', 'button'];
const listeners = [
  {node: 'root', capture: true, name: 'root-capture'},
  {node: 'panel', capture: true, name: 'panel-capture'},
  {node: 'button', capture: false, name: 'button-target'},
  {node: 'panel', capture: false, name: 'panel-bubble'},
  {node: 'root', capture: false, name: 'root-bubble'}
];
const trace = [];
const target = path.at(-1);
const schedule = [
  ...path.map(node => ({node, capture: true})),
  ...[...path].reverse().map(node => ({node, capture: false}))
];
for (const visit of schedule) {
  for (const listener of listeners.filter(x => x.node === visit.node && x.capture === visit.capture)) {
    trace.push({listener: listener.name, target, currentTarget: visit.node});
  }
}
console.assert(trace.map(x => x.listener).join(',') ===
  'root-capture,panel-capture,button-target,panel-bubble,root-bubble');
console.assert(trace.every(x => x.target === 'button'));
console.log(trace.map(x => x.currentTarget).join(' → '));

Failure: phase and stop settings make an update unreachable

If a parent capture listener stops propagation while the child button has a non-capture update listener, the child update may never run. Suitable repairs include removing an unnecessary stop, moving processing to the intended target, or delegating the operation to one parent listener. The repair depends on the intended path. Registering the same update at several points merely to recover a visible result can introduce a double increment for one click. Fix the dispatch design rather than duplicating effects.

Compare a target with no listeners, a single root element without ancestors, and a parent with several matching registrations. Each is a legitimate boundary case rather than automatically an error. A registration for an absent model node or a mutation command that cannot find its target is a separate input failure. Keep four observations distinct: dispatch occurred, a handler ran, the DOM changed, and the result was painted. A single success flag cannot explain which of those stages actually completed.

Exercise: repair stopping and mutation targets independently

In the DOM and events repair task, inspect a configuration where the intended handler is unreachable, then edit capture settings and the stop location. In the other task, correct the node chosen for a mutation. Check invocation order, target, currentTarget, and the changed node, not only the final label. Change parent names and label text in regression cases so that a repair cannot depend accidentally on one fixed ID or a memorized output.

Write a short causal note such as: dispatch starts on button; panel capture sets the stop flag; the button listener is never reached. Pause immediately before and after the flag changes and inspect the state difference. Finally remove the stop and rerun from the initial state. Previous mutations and flags must not survive the reset. A repeatable trace makes the model useful for investigating a missing handler instead of simply presenting one successful event animation.

Try the interactive model

DOM mutations and event dispatch

Loading demo checkpoint…

Reading and practice are recorded separately in this browser, for each language.

Learn this in order

Build your CS foundations · STEP 20

Choose a learning path