Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use the d3.selectAll(...).each() method with ES6 arrow notation #2644

Closed
wil93 opened this issue Nov 18, 2015 · 2 comments
Closed

How to use the d3.selectAll(...).each() method with ES6 arrow notation #2644

wil93 opened this issue Nov 18, 2015 · 2 comments
Milestone

Comments

@wil93
Copy link

wil93 commented Nov 18, 2015

I had this code:

var me = this;
...
d3.selectAll(".region").each(function(d) {
    d3.select(this).style("fill", me.compute_color(...));
})

With ES6, I can use the arrow notation to avoid overwriting this:

d3.selectAll(".region").each(d => {
    d3.select(this).style("fill", this.compute_color(...));
})

However, this code doesn't work anymore because d3 is selecting the wrong element. In fact, I have lost the only reference to the element, because this was not overridden by d3.

How can I change d3.select(this) so that it works?

@mehmetavsar
Copy link

Two possibilities:

  • d object may be holding a property that could be used as a reference (like DOM Object) or a selector string to itself

Or

var mainSelection = d3.selectAll(".region");
mainSelection.each((d,i) => {
  mainSelection[i].style("fill"...  // Not sure if it's indexed.
 // d3.select(mainSelection[i]).style(... // would be my 2nd try
});

@mbostock mbostock added the req label Nov 19, 2015
@mbostock mbostock added this to the 4.0 milestone Nov 19, 2015
@mbostock
Copy link
Member

ES6 arrow functions lexically bind this, which prevents you from being able to access the this context of the selected node set by D3. There’s no way to fix this globally without abandoning the use of this as the selected node; some potential approaches are discussed in #2246.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

3 participants