gpt4 book ai didi

javascript - 将其绑定(bind)到回调函数

转载 作者:行者123 更新时间:2023-11-28 00:00:35 25 4
gpt4 key购买 nike

如何使用 call 或 apply 将其绑定(bind)到回调函数?

    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));
});
},

在某个时刻抛出错误:

类型错误:this.get 不是函数

这应该指的是 Ember Controller 范围,为什么如果我先用 bind(this) 绑定(bind),然后 call(this) 会抛出错误?

最佳答案

为此,您最好使用bind

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

编辑:你仍然犯同样的错误。 Promise 方法 then 接受一个函数引用,因此一旦确定就可以调用它。您要做的就是执行函数并将函数的返回值传递给 then 方法,在本例中是另一个 Promise 对象。

让我们分解一下:

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);
}

关于javascript - 将其绑定(bind)到回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31843547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com