如何将 Backbone 函数作为参数传递

How to pass a Backbone function as a parameter

我需要将 Backbone 视图中的函数传递给同一视图中的另一个函数。我使用了以下方法,它适用于全局函数。但是当关注 Backbone 视图实例时,它不起作用。

我认为问题在于传递的函数具有不正确的上下文 - 请注意 this 在控制台中打印不同的对象。

如何在正确的上下文中正确传递函数和调用函数?

JSFiddle

//Backbone view
mainFunc: function(){
    this.intermediateFunc(this.ABC);
}
intermediateFunc : function(callback){
    console.log(this); //prints the correct view
    callback();
}
ABC : function(){
    console.log(this); //prints 'window' when passed through a function
}

最简单的方法是使用 Function.prototype.bind 将适当的 this 绑定到您的函数。像这样:

mainFunc: function(){
    this.intermediateFunc(this.ABC.bind(this));
}

回调的另一种常见方法是允许调用者提供所需的 thisFunction.prototype.call or Function.prototype.apply 以使用它:

mainFunc: function(){
    this.intermediateFunc(this.ABC, this);
},
intermediateFunc : function(callback, context) {
    console.log(this); //prints the correct view
    if(context)
        callback.call(context);
    else
        callback();
}

这个变体可以假定 context 应该是 intermediateFunc 中的 this:

mainFunc: function(){
    this.intermediateFunc(this.ABC, this);
},
intermediateFunc : function(callback, context) {
    console.log(this); //prints the correct view
    context = context || this;
    callback.call(context);
}

如果您希望 callback 几乎总是您的视图方法之一(或普通函数),这可能会有用。

另一种方法是使用旧的 var _this = this 技巧并将匿名函数传递给 intermediateFunc:

mainFunc: function() {
    var _this = this;
    this.intermediateFunc(function() { return _this.ABC() });
}