'Call class method within D3 method [duplicate]
I have a JS class where I'm using D3. I've created a button element that I need to execute a class function upon being pressed. What is the proper way to do this?
class MyClass{
...
foo(bar){
d3.select("button").on("click",function(){ this.print(bar) });
}
print(text){
console.log(text);
}
}
As far as I know, going within the scope of function(){..} loses the binding of this and the instance of MyClass, because it claims that this.print() is not a function.
Solution 1:[1]
To do it you can save your class instance inside a variable
in my sample
let _this = this;
And use this new variable in your d3 function
class MyClass{
...
foo(bar){
let _this = this;
d3.select("button").on("click",function(){ _this.print(bar) });
}
print(text){
console.log(text);
}
}
Solution 2:[2]
You can use an arrow function to keep the reference to the instance's this context. In the words of the docs:
In arrow functions,
thisretains the value of the enclosing lexical context'sthis.
Your code could thus be rewritten as
d3.select("button").on("click", () => this.print(bar));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jeremy-denis |
| Solution 2 | altocumulus |
