0

I have a problem with the correct usage of 'this'
I have a class called Smartphone, a helper-method to get JSONP data from an API and a fetch method to process the requested data and such. Here's the mentioned part of my Class:

class Smartphone {

fetchData(data, callback) {

    switch (data.action) {
        case "contacts":
            this.getJSONP(data, function (response) {
                if (response.status === "ok") {
                    this._contacts = response.data;
                   // console.log(this._contacts);
                    callback;
                }
            });

            break;
    }

}
 render(tab) {

    this.fetchData({"action": "contacts"}, function () {
    // code will be inserted later, tab unused in this example
    });
    console.log(this._contacts);

}

getJSONP(data, callback) {
    return $.ajax({
        context: this,
        url: 'URL',
        dataType: 'jsonp',
        data: data,
        success: callback
    });
}

}

I tried using bind on the callback in this.getJSONP, on success and a few other things (à la trial and error).

Edit: I forgot to mention the exact problem: I want this._contacts to be the property of the class, i cant use this one in other methods after fetching the data.

Edit 2: added a example for fetchData call.

I also have read the difference between apply/call/bind but can't figure it out how to use it properly. Javascript is pretty confusing to me coming from Java so I would appreciate an explanation very much.
Thanks for you attention.

axeco
  • 17
  • 1
  • 6
  • Instead of `function(response){`, use `response => {`. `function` create a new scope and change the `this` inside it. Arow function doesn't alter `this` so it will still be your class in the callback. – Karl-André Gagnon Mar 13 '18 at 14:03
  • How do you call fetchData? – Musa Mar 13 '18 at 14:11
  • You could also do `function (response) { ... }.bind(this);` – James Mar 13 '18 at 14:12
  • I tried the arrow function and the function (response) { ... }.bind(this);, also added an example for fetchData, my script always returns undefined for _contacts – axeco Mar 13 '18 at 14:17
  • [how do i return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Musa Mar 13 '18 at 14:22
  • thanks for the comments, got it to work now – axeco Mar 13 '18 at 14:30

1 Answers1

0

Have a look here: How to access the correct `this` inside a callback?

And also if you want to call the callback inside your response you have to add the brackets

 if (response.status === "ok") {
          this._contacts = response.data;
          // console.log(this._contacts);
          callback();
 }
Alessandro.Vegna
  • 1,262
  • 10
  • 19