Event Delegation Implementation in Rust
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Event Delegation runs in O(1) time and O(1) space, in Rust as in every other language.
- ✓There is no widget tree and no event loop in std, so there is nothing to delegate to until you build it.
- ✓Indices, not pointers. A reviewer will push back on Rc<RefCell<Node>> with parent links, because that shape builds a reference cycle that never frees and puts a runtime borrow flag in front of every field read.
- ✓The Rust trap: RefCell is where this breaks, and only once a handler mutates the tree. Dispatch takes a shared borrow to walk ancestors; the handler it finds wants to add a seat, remove a row, or register another handler, all of which need borrow_mut() while your walk's Ref guard is still alive.
- ✓The arena is one amortised allocation and the ancestor walk is a run of index loads into contiguous memory, which is cache-friendly in a way a pointer-chasing tree never is.
What Event Delegation actually is
Event Delegation in Rust: what you actually reach for
Rust implementation
use std::collections::HashMap;
/// One Vec holds the hall: children point at parents by index, so walking "up"
/// is index arithmetic, not a chain of Rc clones with a cycle waiting in it.
struct Node {
parent: Option<usize>,
action: Option<&'static str>,
}
struct Hall {
nodes: Vec<Node>,
}
impl Hall {
fn add(&mut self, parent: Option<usize>, action: Option<&'static str>) -> usize {
self.nodes.push(Node { parent, action });
self.nodes.len() - 1
}
/// Nearest ancestor-or-self with an action, bounded at root.
fn closest(&self, mut id: usize, root: usize) -> Option<(usize, &'static str)> {
loop {
if let Some(action) = self.nodes[id].action {
return Some((id, action));
}
if id == root {
return None;
}
id = self.nodes[id].parent?;
}
}
}
fn main() {
let mut hall = Hall { nodes: Vec::new() };
let root = hall.add(None, None);
let row = hall.add(Some(root), None);
let seat = hall.add(Some(row), Some("seat.hold"));
let label = hall.add(Some(seat), None); // the click lands on the label
let mut table: HashMap<&str, fn(usize)> = HashMap::new();
table.insert("seat.hold", |id| println!("holding node {id}"));
// Resolve the path first, then run: nothing is borrowed at call time.
if let Some((id, action)) = hall.closest(label, root) {
if let Some(run) = table.get(action) {
run(id);
}
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Rust-specific trap
Performance in Rust, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Rust type or library should I use for Event Delegation?
There is no widget tree and no event loop in std, so there is nothing to delegate to until you build it. In the browser the answer is two crates, not the standard library: web-sys exposes EventTarget::add_event_listener_with_callback, Event::target and Element::closest, and wasm-bindgen's Closure is what turns a Rust FnMut into a value JavaScript can hold on to. Everywhere else the pattern collapses to what the snippet shows: a Vec<Node> arena with Option<usize> parent links and a HashMap<&str, fn(usize)> dispatch table.
What is the most common Rust mistake when implementing Event Delegation?
RefCell is where this breaks, and only once a handler mutates the tree. Dispatch takes a shared borrow to walk ancestors; the handler it finds wants to add a seat, remove a row, or register another handler, all of which need borrow_mut() while your walk's Ref guard is still alive. That is a runtime panic, already borrowed: BorrowMutError, not a compile error, and it fires only on the code path where a handler happens to mutate, so it survives every test that only reads. Resolve the match first, drop the guards, then call. Reaching for Rc<RefCell<Node>> does not remove the panic, it adds a leak on top of it.
How does Event Delegation actually perform in Rust?
The arena is one amortised allocation and the ancestor walk is a run of index loads into contiguous memory, which is cache-friendly in a way a pointer-chasing tree never is. Nothing allocates per dispatch as long as you return the match instead of collecting the path into a Vec. HashMap defaults to SipHash-1-3, a real per-lookup cost for keys this short, and a match on &str compiles down to length and byte comparisons that usually beat it for a fixed table. Rc costs a non-atomic increment and decrement per clone; RefCell costs a flag check per borrow. Time complexity is O(1) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for GitHub Copilot, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.