In D3.js v4, when registering an event listener through a traditional callback function, this
references the current DOM element:
d3.select("div").on('mouseenter', function() {
d3.select(this).text("Yay");
});
ES6 offers arrow functions, which IMHO make D3.js code a lot more readable because they are very concise. However, traditional callbacks cannot blindly be replaced with arrow functions:
d3.select("div").on('mouseenter', () => {
d3.select(this); // undefined
});
The article "On D3 and Arrow Functions" gives a very good explanation of why this
is not bound as expected. The article suggests using traditional callbacks for code that needs access to the current DOM element.
Is it possible to access the current DOM element from an arrow function?
It is possible to use an ES6 arrow function and access the current DOM element via
d3.event.target
: