Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
672 views
in Technique[技术] by (71.8m points)

ecmascript 6 - D3.js v4: Access current DOM element in ES6 arrow function event listener

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is an idiomatic way of doing this in D3: just use the less famous third argument:

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

And that's the same of:

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

I wrote an example here: d3 v4 retrieve drag DOM target from drag callback when `this` is not available

Here is a demo:

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...