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
211 views
in Technique[技术] by (71.8m points)

javascript - How can I get access to the current selection inside a D3 callback?

How can I get access to the current selection inside a D3 callback?

group.selectAll('.text')
    .data(data)
    .enter()
    .append('text')
    .text((d) => d)
    .attr('class', 'tick')
    .attr('y', (d) => {
      // console.log(this) <-- this gives me window :( but I want the current selection or node: <text>
      return d
    })

I could do a d3.select('.tick') in the callback, since by then I've added a class and can get the node via d3.select, but what if I didn't add the class?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The problem here is the use of an arrow function to access this.

It should be:

.attr("y", function(d){
    console.log(this);
    return d;
})

See here the documentation about arrow functions regarding this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

It says:

An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.target).

To get the current DOM element this in an arrow function, use the second and third arguments combined:

.attr("y", (d, i, n) => {
    console.log(n[i]);
    return n[i];
})

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

...