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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…