D3.js v4: access the current DOM element in the ES6 arrow

In D3.js v4, when registering an event listener through a traditional callback function, it thisrefers to the current DOM element:

d3.select("div").on('mouseenter', function() {
  d3.select(this).text("Yay");
});

ES6 offers arrow functions that IMHO make D3.js code more readable because they are very concise. However, traditional callbacks cannot be seen blindly by arrow functions:

d3.select("div").on('mouseenter', () => {
  d3.select(this); // undefined
});

The article " D3 Functions and Arrows" provides a very good explanation of why it is thisnot 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 ?

+4
2

D3 : :

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

:

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

: d3 v4 DOM , ` this`

:

d3.selectAll("circle").on("mouseover", (d, i, p) => {
        d3.select(p[i]).attr("fill", "maroon")
    })
    .on("mouseout", (d, i, p) => {
        d3.select(p[i]).attr("fill", "seagreen")
    });
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg>
	<circle cx="50" cy="50" r="20" fill="seagreen"></circle>
	<circle cx="125" cy="50" r="20" fill="seagreen"></circle>
	<circle cx="200" cy="50" r="20" fill="seagreen"></circle>
</svg>
Hide result

, , , .

, d3.event.target, , . :

d3.selectAll("circle").each(()=>d3.select(d3.event.target).attr("fill", "red"))
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg>
	<circle cx="50" cy="50" r="20" fill="seagreen"></circle>
	<circle cx="125" cy="50" r="20" fill="seagreen"></circle>
	<circle cx="200" cy="50" r="20" fill="seagreen"></circle>
</svg>
Hide result

:

d3.selectAll("circle").each((d,i,p)=>d3.select(p[i]).attr("fill", "red"))
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg>
	<circle cx="50" cy="50" r="20" fill="seagreen"></circle>
	<circle cx="125" cy="50" r="20" fill="seagreen"></circle>
	<circle cx="200" cy="50" r="20" fill="seagreen"></circle>
</svg>
Hide result
+3

ES6 DOM d3.event.target:

d3.select("div").on('mouseenter', () => {
  d3.select(d3.event.target).text("Yay, this works!");
});
0

Source: https://habr.com/ru/post/1666132/


All Articles