Rah*_*thy 7 d3.js ecmascript-6 arrow-functions
在D3.js v4中,通过传统的回调函数注册事件监听器时,this
引用当前的DOM元素:
d3.select("div").on('mouseenter', function() {
d3.select(this).text("Yay");
});
Run Code Online (Sandbox Code Playgroud)
ES6提供了箭头功能,恕我直言,使得D3.js代码更具可读性,因为它们非常简洁.但是,传统的回调不能盲目地用箭头函数替换:
d3.select("div").on('mouseenter', () => {
d3.select(this); // undefined
});
Run Code Online (Sandbox Code Playgroud)
文章"论D3和箭头函数 "给出了一个非常好的解释,说明为什么this
没有按预期约束.本文建议对需要访问当前DOM元素的代码使用传统的回调.
是否可以从箭头函数访问当前的DOM元素?
在D3中有一种惯用的方法:只使用不那么有名的第三个参数:
selection.on("mouseenter", (d, i, nodes) => {
d3.select(nodes[i]);
});
Run Code Online (Sandbox Code Playgroud)
那是相同的:
selection.on("mouseenter", function() {
d3.select(this);
});
Run Code Online (Sandbox Code Playgroud)
我在这里写了一个例子:当`this`不可用时,d3 v4从拖动回调中检索拖动DOM目标
这是一个演示:
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")
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)
实际上,如果你查看你链接的文章的结尾,他给出了相同的解决方案.
你提出的解决方案,d3.event.target
尽管事件侦听器的工作,不工作的几种情况.例如:
d3.selectAll("circle").each(()=>d3.select(d3.event.target).attr("fill", "red"))
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)
但是相同的代码使用第三个参数:
d3.selectAll("circle").each((d,i,p)=>d3.select(p[i]).attr("fill", "red"))
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)
可以使用 ES6 箭头函数并通过以下方式访问当前 DOM 元素d3.event.target
:
d3.select("div").on('mouseenter', () => {
d3.select(d3.event.target).text("Yay, this works!");
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1234 次 |
最近记录: |