Scope in asynchronous call (Javascript)

Asked

Viewed 62 times

3

Suppose I had the following method:

this.loadCustomers = function(){
    Request.get("php/loadCustomersAction.php", (function(error, data){
        if(!error)
            this.setCustomers(data);
    }).bind(this));
};

where "Request.get" is a method that performs asynchronous calls.

It is possible to imagine that the "this" in

this.setCustomers()

can maintain the same scope as

this.loadCustomers()

without the help of bind when establishing callback and without making the function synchronous? If yes, how could it be done?

1 answer

3


There are ways around this without using the .bind, but remember that it may be the case that the .bind be the most useful/simple.

Alternatives:

  • Using alias var self = this

ie: keeping a reference to the this

this.loadCustomers = function(){
    var self = this;
    Request.get("php/loadCustomersAction.php", function(error, data){
        if(!error) self.setCustomers(data);
    });
};
  • Using () => {}

ie: Arrow functions

this.loadCustomers = function(){
    Request.get("php/loadCustomersAction.php", (error, data) => {
        if(!error) this.setCustomers(data);
    });
};

There may be more alternatives, but it depends on how Req.get is implemented. It may be worth testing call this Req.get forcing the context:

this.loadCustomers = function(){
    Request.get.call(this, "php/loadCustomersAction.php", function (error, data){
        if(!error) this.setCustomers(data);
    });
};

that with some luck allows, if the implementation allows, to pass the context to the callback.

  • 1

    I ended up opting for the use of bind, even. It seemed to me the least risky way to work. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.