Goal: connect a click to execution in Rust
After rendering a static DOM, investigate which function an input event causes to run. In wave four the interface forwards a target identifier and Rust dispatch_event handles the path and registered listeners in the lesson DOM. The interface does not implement the lesson's behavior using host JavaScript callbacks. Follow the connection from a registered function through the Rust evaluator to mutation of the same DOM.
Distinguish the event target, the node currently being processed, and the dispatch phase. The target does not become an ancestor merely because an ancestor's listener is executing. Compare the event trace with Rust path traversal and explain why one listener ran before another. A button visibly changing proves much less than the ordering contract.
Separate listener registration from dispatch
The subset registers click listeners with addEventListener, a named function, and an optional capture boolean. Registration stores information; it does not execute the function body. Identify the node identifier, event type, function reference, and phase selection used later during dispatch. Confusing registration with invocation can run a handler during initialization or invoke a listener associated with the wrong node.
This is a bounded click-dispatch model. Do not infer support for the entire DOM event system, Shadow DOM boundaries, default actions, or arbitrary listener options. The official DOM specification supplies primary terminology and algorithms; the Rust implementation defines this lesson's supported surface. Explicitly rejecting an unsupported option preserves the causal story better than accepting syntax whose behavior is absent.
Determine the path, then traverse in two directions
Parent links yield an ancestor path from the target. Capture approaches the target from outside; bubble travels back outward from the target. Both traversals use the same structural path in opposite directions. A sibling is not on that path, even when it appears next to the clicked element. The parent relationships stored in the Rust arena, rather than screen proximity, determine dispatch order.
Keep the path model explicit when listeners mutate content. Updating textContent and deciding the current event's target path are different responsibilities. Inspect identifier stability and when the path is established. Repeatedly locating a node by its visible label during dispatch could accidentally redirect an event after a listener changes that label, producing behavior unrelated to the original click.
Worked trace: ordering across three nodes
Consider root containing panel containing button, with one capture listener and one bubble listener on each. Without stopping, predict the inward capture sequence followed by the outward bubble sequence. Explain why button appears in both listener groups without describing this as two separate clicks. Distinguishing target listeners from ancestor listeners makes the trace understandable.
Then call stopPropagation in panel's capture listener and inspect where movement to other nodes stops. This operation does not delete every registered listener. It is also distinct from stopImmediatePropagation, which concerns other listeners on the same target. The worked table and standalone snippet use one listener per phase per node so they isolate the basic path-stopping contract without claiming every standard event behavior.
| Order | Without stopping | Stop at panel capture |
|---|---|---|
| 1 | root capture | root capture |
| 2 | panel capture | panel capture → stop |
| 3 | button capture | Not dispatched |
| 4 | button bubble | Not dispatched |
| 5–6 | panel bubble → root bubble | Not dispatched |
Observe event sequence order and failure locations
Structured input can contain initial HTML, CSS, JavaScript, and an ordered event list. Initial script execution registers listeners before events are dispatched. Two clicks within one request differ from resetting and running one click twice: the second event in a request observes state changed by the first. A counter is a useful probe for that continuity.
Use a target with ancestors as the normal case. Boundaries include a node without listeners and an empty event list. A missing target is a failure case, and the request accepts at most sixteen events. Check where a longer list is rejected rather than assuming it ran. Distinguish handler runtime failure from malformed input and establish which events completed from the returned result and trace.
Runnable Rust: path and stopping contracts
This standalone host Rust program checks ordering and stopping on a predetermined path. It omits HTML parsing, listener registration, function evaluation, and multiple listeners on the same node. Its explicit assumption is one listener for each phase at every path node. Connect that small contract to dispatch_event without mistaking it for a complete DOM event implementation.
The path is ordered from outside to target, and reverse iteration models bubble traversal. Stopping at node two leaves only nodes one and two in the capture log. The empty-path assertion checks termination of this helper; it does not mean the actual engine accepts an invalid target. Record the helper's assumptions separately from the validation performed by the complete implementation. An additional target-stop assertion runs both capture and bubble listeners on target three, then prevents traversal back to ancestors.
#[derive(Clone, Copy, PartialEq, Debug)]
enum Phase { Capture, Bubble }
fn dispatch(path: &[u32], stop_at: Option<u32>) -> Vec<(u32, Phase)> {
let mut log = Vec::new();
for &id in path {
log.push((id, Phase::Capture));
if stop_at == Some(id) && Some(id) != path.last().copied() { return log; }
}
for &id in path.iter().rev() {
log.push((id, Phase::Bubble));
if stop_at == Some(id) { return log; }
}
log
}
fn main() {
let path = [1, 2, 3]; // root, parent, target; one listener per phase
let full = dispatch(&path, None);
assert_eq!(full.iter().map(|x| x.0).collect::<Vec<_>>(), vec![1,2,3,3,2,1]);
let stopped = dispatch(&path, Some(2));
assert_eq!(stopped, vec![(1,Phase::Capture),(2,Phase::Capture)]);
let at_target = dispatch(&path, Some(3));
assert_eq!(at_target, vec![(1,Phase::Capture),(2,Phase::Capture),
(3,Phase::Capture),(3,Phase::Bubble)]);
assert!(dispatch(&[], None).is_empty());
println!("full={} stopped={}", full.len(), stopped.len());
}Make side-effect order explainable
If every listener only adds one to a counter, the final value may hide ordering mistakes. Log phase and name with console.log, or append distinct characters, so capture and bubble produce distinguishable observations. Detailed trace output is bounded, so a long program need not expose every intermediate operation. Prefer a short input that makes the disputed order visible with minimal instrumentation.
Rendering after a handler changes textContent or an attribute is a separate boundary. Determine whether dispatch failed, function execution failed, or DOM mutation succeeded but rendering differed. Associate target identifier, invoked function, changed node, and rendering result. This narrows an apparently unresponsive button to a specific stage instead of treating every symptom as a visual defect.
Exercise: move the stopping point
Create a three-level DOM and register named listeners on its nodes. Predict the sequence without stopping, then move stopPropagation from the outer node to the parent and finally the target. Record expected listener names before each run and compare Rust trace phases and functions. Add a listener on an unrelated sibling and explain why the target's path excludes it.
Next provide two events and check whether the second reads state changed by the first. Replace the target ID with a missing value and record the diagnostic. Submit the parent relationships, registration table, predicted and observed sequences, and failure evidence. As an extension, let a listener replace text and explain the distinction between the event's structural path and the changing DOM content.