使用 Backbone 将 "this" 传递给 bootbox 回调函数

4

我正在使用Backbone和bootbox。 这是我的视图内的代码:

    confirm : function(result) {
        if (result === true) { 
            var that = this;
            this.model.set({completed: '1'}); // Exception here
            this.model.save(
                    null, {
                success: function (model, response) {
                    Backbone.history.navigate("index", true);
                },
                error: function(model, response) {
                    that.model.set({completed: '0'});
                    var responseObj = $.parseJSON(response.responseText);
                    bootbox.alert(responseObj.message);
                }
            });
        }
    },

    completeProcess : function(event) {
        event.preventDefault();
        this.model.set({completed: '1'});
        bootbox.confirm("Confirm?", this.confirm );
    }

我遇到了这个错误:

Uncaught TypeError: Cannot call method 'set' of undefined

有没有一种方法可以从视图中传递引用?

你看过 _.bind 吗? - Jack
@Jack _.bind 相对于标准的 Function.prototype.bind 有什么优势?向后兼容性吗?我没有看到其他内容。 - Justin Morgan
@JustinMorgan 如果标准(或者说是本地的bind可用,underscore 将使用它。 - Jack
2个回答

3
作为的一个依赖,你可以使用它的_.bind特性来处理
_.bind(function, object, [*arguments])

将函数绑定到对象上,这意味着每当调用该函数时,this 的值将是该对象。
可选地,传递参数到函数中以预先填充它们,也称为局部应用程序。

在您的情况下,可能会像这样:

completeProcess : function(event) {
  event.preventDefault();
  this.model.set({completed: '1'});
  bootbox.confirm("Confirm?", _.bind(this.confirm, this));
}

一个问题:关于由bootbox传递的原始参数“result”,它是被忽略了吗? - dierre
所以我试了一下,但我仍然得到confirm的结果,而不是这个引用。我需要两个都。 - dierre

0

或者,你可以像这样做,以保留原始的“this”:

var _this = this;

bootbox.confirm({
    message: Message ,
    callback: function(result) {
        console.log(this + " != " + _this);
    },

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接