我绑定了我的骨干模型的变化事件。
this.model.on( "change", this.render, this );
有时我想获取模型的最新版本并强制渲染视图。所以我这样做
this.model.fetch();
不幸的是,如果新数据与先前存储在模型中的数据不同,model.fetch()仅触发change事件。
当获取完成时,我怎样才能始终触发this.render回调,无论它是否触发更改事件?
在此先感谢您的帮助
我绑定了我的骨干模型的变化事件。
this.model.on( "change", this.render, this );
有时我想获取模型的最新版本并强制渲染视图。所以我这样做
this.model.fetch();
不幸的是,如果新数据与先前存储在模型中的数据不同,model.fetch()仅触发change事件。
当获取完成时,我怎样才能始终触发this.render回调,无论它是否触发更改事件?
在此先感谢您的帮助
你可以使用 $.ajax
成功回调,但你也可以只听Backbone sync
和 error
模型上的事件。 sync
成功调用服务器后触发, error
在调用服务器失败后触发。
this.model.on('sync', this.render, this);
this.model.on('error', this.handleError, this);
该 fetch
方法可以选择接受成功和错误回调;最简单的解决方案是给你看视图 render
在成功回调中。您也可以使用返回的jqXHR承诺,但是如果有一种情况是AJAX会成功(按照jQuery)但模型初始化失败,那么这种使用可能会有问题。
我不知道你的代码结构是什么,但是如果你在视图中提取你的模型,你可以使用这样的东西
var that = this;
this.model.fetch().done(function () {
that.render();
});
否则,如果您在视图之外取得模型,您可以将您的承诺传递给您的视图并制作类似的内容
var promise = model.fetch();
// other code here
var view = new View({
model: model,
promise: promise
});
在视图中,例如在初始化中
View = Backbone.View.extend({
initialize: function(){
this.options.promise.done(function () {
// your code here
});
}
});
这个解决方案怎么样:
// emit fetch:error, fetch:success, fetch:complete, and fetch:start events
fetch: function(options) {
var _this = this;
options = options || {};
var error = options.error;
var success = options.success;
var complete = options.complete;
options.error = function(xhr, textStatus, errorThrown) {
_this.trigger('fetch:error');
if (error) error(xhr, textStatus, errorThrown);
};
options.success = function(resp) {
_this.trigger('fetch:success');
if (success) success.call(options.context, resp);
};
options.complete = function() {
_this.trigger('fetch:complete');
if (complete) complete();
};
_this.trigger('fetch:start');
return Backbone.Model.prototype.fetch.call(this, options);
}