[英]How can I set context of the error handler of Backbone model fetch?
我正在使用路由器来组织我的Backbone应用。 在我的编辑路线中,我在模型实例上调用fetch来获取编辑表单的模型数据:
App.Router = Backbone.Router.extend({
routes: {
"": "index",
"edit(/:id)": "edit"
},
index: function () {
_.bindAll(this, "getItemByID", "onModelFetchError", "showError");
},
edit: function (id) {
this.formEditItem = new App.Views.FormEditItem({model: this.getItemByID(id), parent: this});
},
getItemByID: function(id) {
var item = new App.Models.Item({id: id});
item.fetch({
success: function(model, response, options) {
console.log('Success');
return model;
},
error: this.onModelFetchError
})
},
onModelFetchError: function (model, response, options) {
this.showError(response.responseText);
},
showError: function(msg) {
this.error = new App.Views.Error({parent: this, message: msg});
}
});
fetch调用工作正常,但是在处理错误时遇到了麻烦。 我想实例化一个错误视图并在其中显示消息。 但是,当我尝试此代码时,出现“未捕获的TypeError:对象[object global]没有方法'showError'”。 似乎将onModelFetchError分配为获取错误的处理程序,即使我使用_.bindAll将其绑定到路由器,也将其置于全局范围内。
有什么简单的方法可以确保onModelFetchError保留在路由器范围内?
试试看
getItemByID: function(id) {
var item = new App.Models.Item({id: id});
var self = this; // this changed
item.fetch({
success: function(model, response, options) {
console.log('Success');
return model;
},
error: self.onModelFetchError // this changed
})
},
您正在调用由路由“”触发的index函数内部的_.bindAll()
,因此,如果不触发该路由,它们将永远不会绑定到上下文对象。 我建议为路由器创建一个初始化方法,以便您可以为路由器中的任何路由绑定所有功能。
initialize: function() {
_.bindAll(this, "getItemByID", "onModelFetchError", "showError");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.