d3 / d3-selection

Transform the DOM by selecting elements and joining to data.

Home Page:https://d3js.org/d3-selection

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Event management and arrow function (v6)

peterith opened this issue · comments

d3 version 6 has made significant changes to event management. It is no longer possible to use arrow function like this:

selection.on("mouseenter", (d, i, nodes) => {
    d3.select(nodes[i]);
});

This technique was used to replicate this:

selection.on("mouseenter", function() {
    d3.select(this);
});

D3 6.0 migration guide made no mention of how to use arrow function for event management when this is required.

Try

selection.on("mouseenter", (event) => {
    d3.select(event.currentTarget);
});

It is mentioned in https://observablehq.com/@d3/d3v6-migration-guide#events

Note that event.currentTarget gives access to the element to which the listener is bound and can replace this in arrow functions: selection.on("click", (event, d) => { console.log(event.currentTarget); })

Under what circumstances is currentTarget not defined in event? I'm using call(d3.drag().on("start", dragstarted)) but dragstarted isn't showing currentTarget in its event...

@t3db0t For custom events such as d3-drag you’ll need event.sourceEvent.currentTarget.

Ah—thank you. Now I'm seeing that currentTarget works for start, but NOT for drag, but toElement does work for drag. Are any of these documented somewhere?