将此绑定到回调函数 [英] Bind this to a callback function
问题描述
如何通过调用或应用将其绑定到回调函数?
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));
});
},
在某些时候引发错误:
TypeError:this.get不是函数
TypeError: this.get is not a function
这应该指的是Ember Controller作用域,为什么我先用bind(this)绑定然后调用(this)会引发错误?
This should referring to Ember Controller scope, why if I bind first with bind(this) and then call(this) throws an error?
推荐答案
为此,最好使用bind
.
function doSomething(){
return authorize().then((function(){
}).bind(this));
}
bind()函数创建一个新函数(绑定函数),该函数具有与使用this值调用它的函数(绑定函数的目标函数)相同的函数主体(ECMAScript 5术语中的内部调用属性)绑定到bind()的第一个参数,该参数不能被覆盖.
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.
您仍然在犯同样的错误. promise方法then
具有函数引用,因此一旦解决,便可以调用它.您正在执行的是执行该函数并将该函数的返回值传递给then
方法,在这种情况下,该返回值是另一个promise对象.
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.
让我们分解一下:
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);
}
这篇关于将此绑定到回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!