I have a class and in the init method I'm setting up a click event, and inside that event I want to call a method on the class and I can't figure out how to do it or if it's even possible. Here's code that shows the structure of what I'm trying. in the classes init() function, after the ajax returns I'm setting up a click event, and in that callback I want to call the class's classFn() function. I've tried binding this, I've tried self = this and binding that, arrow functions (which I didn't expect to work but figured I'd give it a try), etc.
class MyClass {
constructor() {
this.a = '';
}
init() {
....
$.getJSON(url, function(data) {
$(mySelector).click(function() {
classFn();
});
});
}
classFn() {
....
}
}
function
changes the meaning of this
. One way to fix the problem is to use bind
. However, you'd have to use it twice, because you have two layers of function
. A simple way to solve it is to use arrow functions, which do not change this
:
class MyClass {
constructor() {
this.a = '';
}
init() {
....
$.getJSON(url, (data) => {
$(mySelector).click(() => {
this.classFn();
});
});
}
classFn() {
....
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With