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

标签 javascript jquery backbone.js

我需要将 Backbone View 中的函数传递到同一 View 中的另一个函数。我使用了以下方法,该方法适用于全局函数。但当涉及到 Backbone View 实例时,它就不起作用了。

我认为问题在于传递的函数具有不正确的上下文 - 请注意 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 绑定(bind)到您的函数。像这样的事情:

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

回调的另一种常见方法是允许调用者提供所需的 thisFunction.prototype.callFunction.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);
}

如果您期望回调几乎始终是 View 的方法之一(或普通函数),这可能会很有用。

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

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

关于javascript - 如何将 Backbone 函数作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40734501/

相关文章:

angularjs - 如何创建基于 Node JS、MongoDB、Sails JS 的动态前端

json - underscore.js - 对象不支持此属性或方法 - ie8

javascript - 在 Backbone Stickit 中结合使用 visible 和 onGet

定义元素后的 Javascript 事件

javascript - html2canvas 不在子 div 中显示图像

javascript - Rails/Javascript : Data attribute not returned through partial, 但存在于 DOM 中

jquery - 受边距影响的 clientX/Y - 扭曲 jQuery/CSS 游标效果

javascript - Google 官方测试页上的 Google Plus 登录按钮错误事件

javascript - 如何在另一个字符之前插入一个字符?

javascript - 无法删除事件监听器