0

I have a javascript class to manage my API calls (here TimelinesManager), and I need to call a method of my manager (same class, named arrayToObject) inside the XMLHttpRequest.onload.

I tried to access it with this.arrayToObject() and TimelinesManager.arrayToObject() but I get an error meaning that it's not a function (TypeError: this.arrayToObject is not a function).

class TimelinesManager {

  getTrends(access_token, start, limit, callback) {
    // Create a request to API
    var request = new XMLHttpRequest();
    request.open('GET', 'https://api.extopy.com/timeline/trends.php', true);
    request.onload = function () {
      var data = JSON.parse(this.response);
      if (request.status == 200) {
        // Here I try to access to my class method
        callback(this.arrayToObject(data));
      }
    };
    request.send();
  }

  // The method I want to call
  arrayToObject(data) {
    // Here I proceed my data
  }

}

How can I access to this class method?

Nathan Fallet
  • 321
  • 2
  • 16
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Andreas Dec 31 '18 at 18:29

1 Answers1

1

Try this. We need to grab this into a variable. As inside the request this refers to the request

class TimelinesManager {

  getTrends(access_token, start, limit, callback) {
    // Create a request to API
  
    let self = this;
    var request = new XMLHttpRequest();
    request.open('GET', 'https://api.extopy.com/timeline/trends.php', true);
    request.onload = function () {
      var data = JSON.parse(this.response);
      if (request.status == 200) {
        // Here I try to access to my class method
        callback(self.arrayToObject(data));
      }
    };
    request.send();
  }

  // The method I want to call
  arrayToObject(data) {
    // Here I proceed my data
  }

}
Bibberty
  • 4,670
  • 2
  • 8
  • 23