Click, datum, and removing a listener
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.
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.
Rewrite it with delegation: one listener on the svg. What changes when a click lands on the background?
Explain it without notes
What arguments does a D3 7 listener receive?
Why does a listener added with addEventListener run three times after three draw calls, but one added with on run once?
When is event delegation better than a listener per bar?
Preview
Console
Nothing logged yet.Expected console output
click on Tue | event.type: click | target is this: true | this: rect
message: Tue: 3992 rides
click on Tue* | event.type: click | target is this: true | this: rect
after on('click', null) the message is still: Tue*: 1 rides
listener getter: undefined