Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 5.6 — Events in D3
Data Visualization · Example 2 of 3

Double-binding, delegation and namespaces

selection.on("click", (event, d) => ...) attaches a listener to every selected mark, and gives it the browser's event and the mark's datum. Learn the version 7 form, how to remove listeners, why re-running draw must not stack them, and when one listener on the parent beats one per mark.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a draw(rows) that makes bars and a click listener that writes the station name into #name. Make sure calling it three times leaves one listener per bar.

02

Rewrite it with delegation: one listener on the svg. What changes when a click lands on the background?

Explain it without notes

01

What arguments does a D3 7 listener receive?

02

Why does a listener added with addEventListener run three times after three draw calls, but one added with on run once?

03

When is event delegation better than a listener per bar?

Double-binding, delegation and namespaces

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

after 3 draws and one click: d3 handler ran 1 time, raw handler ran 3 times
delegated click on S13
delegated handler ran 1 time (the background click was ignored)
a
b
b