我正在使用 Backbone 和 bootbox。 这是我在 View 中的代码:
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
有没有办法从 View 传递引用?
最佳答案
作为underscore是 backbone 的依赖项你可以使用它的 _.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));
}
关于javascript - 使用 Backbone 将 "this"传递给引导框回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17702422/