Understanding Event Listeners in D3 v6
In D3, event listeners are used to trigger actions when specific events occur on elements. When working with data-bound elements, it is important to access the associated data during event handling. This is where the change in event listener pattern between D3 v5 and D3 v6 comes into play.
D3 v5 and Earlier
In D3 versions 5 and earlier, the following pattern was used:
selection.on("eventType", function(d, i, nodes) { ... })
Here, d represents the datum of the element triggering the event, i is its index, and nodes is the current group of elements. Event information could be accessed within the event listener using d3.event.
D3 v6 and Beyond
In D3 v6, the pattern has been modified to:
selection.on("eventType", function(event, d) { ... })
Now, the event is passed directly to the listener as the first parameter, and the datum is the second parameter. As a result, the d3.event global variable has been removed.
Accessing the Datum
To retrieve the bound datum of the node that triggered the event in D3 v6, simply use the d parameter in the event listener function. This is demonstrated in the corrected code below:
<code class="js">node.on("mouseover", (event, d) => { console.log(d.id); });</code>
Other Notable Changes
The above is the detailed content of How Did Event Listeners Change in D3 v6 and Beyond?. For more information, please follow other related articles on the PHP Chinese website!