Bind this to a callback function

2019-08-07 19:55发布

How can I bind this to a callback function, using call or apply?

    beforeModel: function(params){

        return this.get('session').authenticate().then(function(){
            this.findClient(params);
        }.bind(this)).catch(function(err){
          //retrieve new session
          return this.get('session').authorize().then(function(){
            this.findClient(params);
          }.call(this));
        });
    },

Throws an error at some point:

TypeError: this.get is not a function

This should referring to Ember Controller scope, why if I bind first with bind(this) and then call(this) throws an error?

2条回答
放荡不羁爱自由
2楼-- · 2019-08-07 20:15

You are better using bind for that.

function doSomething(){
    return authorize().then((function(){

       }).bind(this));
}

The bind() function creates a new function (a bound function) with the same function body (internal call property in ECMAScript 5 terms) as the function it is being called on (the bound function's target function) with the this value bound to the first argument of bind(), which cannot be overridden.

MDN

Edit: You are still making the same mistake. The promise method then takes a function reference, so it can call it once it's settled. What you are doing is executing the function and passing to the then method the returned value of the function which in this case is another promise object.

Lets break it down:

beforeModel: function(params) {
  //Function to be passed down to your promise to find a Client.
  //Note that nothing gets passed down to the next step once the promise gets settled.
  var fClient = function() {
    this.findClient(params);
  };
  //We want this to be this (of beforeModel function).
  fClient = fClient.bind(this);

  //I have no idea what you are trying to do with the catch...
  var reAttachPromise = function() {
    return this.get('session').authorize().then(fClient);
  };
  //We want this to be this (of beforeModel function).
  reAttachPromise = reAttachPromise.bind(this);

  return this.get('session').authenticate().then(fClient).catch(reAttachPromise);
  //can be reduced to:
  // return reAttachPromise().catch(reAttachPromise);
}
查看更多
走好不送
3楼-- · 2019-08-07 20:25
    }.bind(this)).catch(function(err){
      //retrieve new session
      return this.get('session').authorize().then(function(){
        this.findClient(params);
      }.call(this));
    }.bind(this)); //!!

!-commented line was changed by me. You bound the success function correctly, but not the failure function. Easy thing to miss!

查看更多
登录 后发表回答