Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6: How to call a class function from a callback function [duplicate]

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() {
    ....
  }
}
like image 271
kombat Avatar asked Jan 03 '23 19:01

kombat


1 Answers

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() {
    ....
  }
}
like image 140
Aurel Bílý Avatar answered Jan 05 '23 17:01

Aurel Bílý