0

I was trying to call a function inside a class function. Like the following code. I want to call addMarks in my init() function. But it threw this error

$.get(...).bind is not a function

class MapManager {
  init(){
    $('#search').click(function(event) {
      if(start && destination){
        $.get('routes/search', {data: 123}, function(data, textStatus, xhr) {
          this.addMarks(data.data);
        }).bind(this);
      }
    });
  }

  addMarks(locations){
    ...
  }
}
rj487
  • 4,476
  • 6
  • 47
  • 88

2 Answers2

0

You're binding this to $.get there, instead of the successFn.

Or else, you can always assign this beforehand and access it inside the successFn scope.

E.g.

class MapManager {
  init(){
    let self = this; // <-- assign it here

    $('#search').click(function(event) {
      if(start && destination){
        $.get('routes/search', {data: 123}, function(data, textStatus, xhr) {
          // Yes! I can access 'self' here because it is defined where I am defined.
          self.addMarks(data.data);
        });
      }
    });
  }

  addMarks(locations){
    console.log(":: addMarks");
  }
}
choz
  • 17,242
  • 4
  • 53
  • 73
0

since you're using class so therefore modern javascript, you can forget bind altogether, using arrow function notation

class MapManager {
  init(){
    $('#search').click((event) => {
      if(start && destination){
        $.get('routes/search', {data: 123}, (data, textStatus, xhr) => {
          this.addMarks(data.data);
        });
      }
    });
  }

  addMarks(locations){
    ...
  }
}
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87