这是我的模型视图和集合:
window.Report = Backbone.Model.extend({});
window.ReportCollection = Backbone.Collection.extend({
model: Report,
initialize: function(properties){
this.url = properties.url;
}
});
window.ReportCollectionView = Backbone.View.extend({
initialize: function(){
this.collection.reset();
this.render();
},
render: function(){
var self = this;
this.collection.fetch({
success: function(){
self.collection.each(function(model){
//pass model to subview
});
}
}
});
}
});
在代码的另一部分,我使用实例化上述对象
var reportCollection = new ReportCollection({url:someURL});
var reportCollectionView = new ReportCollectionView({collection:reportCollection});
'someURL' 是一个基于 REST 的 URL,它返回对象的 JSON 列表
到目前为止,一切看起来都不错。我想要实现的是:我必须能够通过更改 url 来刷新"报告集合",这应该会触发更新的"报告集合视图"。感谢您的任何指示
我想
您可以在集合中添加一个更改url
并强制fetch
的方法:
window.ReportCollection = Backbone.Collection.extend({
//...
changeUrl: function(url) {
this.url = url;
this.fetch();
}
});
然后绑定到视图中的"reset"
事件:
window.ReportCollectionView = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'render');
this.collection.on('reset', this.render);
this.collection.reset();
},
//...
});
然后,如果您这样做:
c = new ReportCollection(...);
v = new ReportCollectionView({ collection: c, ... });
您将获得渲染的视图,然后您可以:
c.changeUrl(...);
以设置新的 URL,这将触发对v
的render
调用。