D3.js v4:访问ES6箭头函数事件监听器中的当前DOM元素

时间:2017-01-08 12:22:13

标签: d3.js ecmascript-6 arrow-functions

在D3.js v4中,当通过传统的回调函数注册事件监听器时,onValueChanged引用当前的DOM元素:

this

ES6提供箭头功能,恕我直言使D3.js代码更具可读性,因为它们非常简洁。但是,传统的回调不能盲目地用箭头函数替换:

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

文章" On D3 and Arrow Functions"给出了d3.select("div").on('mouseenter', () => { d3.select(this); // undefined }); 未按预期约束的原因的非常好的解释。本文建议对需要访问当前DOM元素的代码使用传统的回调。

是否可以从箭头功能访问当前DOM元素

2 个答案:

答案 0 :(得分:7)

在D3中有一种惯用方式:只使用不太知名的第三个​​参数

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

那就是:

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

我在这里写了一个例子:d3 v4 retrieve drag DOM target from drag callback when `this` is not available

这是一个演示:



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>
&#13;
&#13;
&#13;

实际上,如果你查看你链接的文章的结尾,他会提供相同的解决方案。

您的proposed solutiond3.event.target,尽管为事件听众工作,但在某些情况下无法正常工作。例如:

&#13;
&#13;
d3.selectAll("circle").each(()=>d3.select(d3.event.target).attr("fill", "red"))
&#13;
<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>
&#13;
&#13;
&#13;

但是相同的代码使用第三个参数:

&#13;
&#13;
d3.selectAll("circle").each((d,i,p)=>d3.select(p[i]).attr("fill", "red"))
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

可以使用ES6箭头功能并通过this访问当前DOM元素:

d3.event.target