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

我收到此错误:

未捕获的类型错误:无法调用未定义的方法“设置”

有没有办法从视图中传递参考?

4

2 回答 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));
}
于 2013-07-17T14:59:49.427 回答
0

或者,你可以做这样的事情来坚持原来的“这个”:

var _this = this;

bootbox.confirm({
    message: Message ,
    callback: function(result) {
        console.log(this + " != " + _this);
    },
于 2015-08-27T13:16:47.800 回答