2013-07-17 36 views
4

我使用Backbone和bootbox。 这是我的代码视图中:通过Backbone将“this”传递给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

有没有办法通过视图中的参考?

+0

你看过[_.bind](http://underscorejs.org/#bind)吗? – Jack

+0

@Jack标准'Function.prototype.bind'上'_.bind'的值是多少?向后兼容?我什么都看不到。 –

+0

@JustinMorgan如果标准(或者说一个* native *)'bind'可用,则下划线将使用它。 – Jack

回答

3

由于的依赖,你可以使用它的_.bind功能:

_.bind(function, object, [*arguments]) 

Bind a function to an object, meaning that whenever the function is called, the value of this will be the object.
Optionally, pass arguments to the function to pre-fill them, also known as partial application.

你的情况,这可能是这样的:

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

一个问题:bootbox传递的原始参数“结果”怎么样?我的意思是,它被忽略了吗? – dierre

+0

所以我尝试了,但我仍然从确认而不是这个参考的结果。我需要两个。 – dierre

+0

对不起!明白了,明白了。非常感谢你! – dierre

0

或者,你可以做些什么像这样挂在原来的'这':

var _this = this; 

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