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,075
  • 6
  • 39
  • 80

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
  • 16,299
  • 3
  • 46
  • 69
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
  • 1
  • 4
  • 64
  • 78