【发布时间】:2017-07-20 22:24:46
【问题描述】:
我正在尝试使用一个集合生成多个视图,并且每 5 秒获取一个。
下面是一个工作示例,但两个视图在获取时都会刷新。 我可以将响应拼接成多个 url,但我想尽量减少请求的数量。
我当前的问题是,当重新获取集合时,我不希望所有视图每 5 秒重新渲染一次,只有关联的视图发生了变化。 我尝试在集合中创建多个模型并在解析函数中添加正确的对象,但没有任何运气。
回复:
{
"json-1": {
"sub_1": "3",
"sub_2": [],
},
"json-2": {
"sub_1": [],
"sub_2": "1",
},
}
// 客户端
const APICollection = Backbone.Collection.extend({
initialize: (models, options) => {
this.id = options.id;
},
url: () => {
return 'https://url.url/' + this.id;
},
model: APIModel,
parse: (resp) => {
return resp;
},
});
const ViewOne = Backbone.View.extend({
initialize: function () {
this.collection.bind('sync', this.render, this);
this.update();
_.bindAll(this, 'update');
},
render: function (n, collection) {
// Render view
},
update: function () {
let self = this;
this.collection.fetch({
update: true, remove: false, success: function () {
setTimeout(self.update, 5000);
}
});
}
});
// Also updates when re-fetched
const ViewTwo = Backbone.View.extend({
initialize: function () {
this.collection.bind('sync', this.render, this);
},
render: function (n, collection) {
// Render function
}
});
let col = APICollection([], {id: 'someid'});
new ViewOne({collection: col, el: $("#one")});
new ViewTwo({collection: col, el: $("#two")});
**更新
澄清:“只有关联的视图发生了变化”。我的意思是“ViewOne”应该只在“json-1”发生变化时重新渲染,而“ViewTwo”不应该重新渲染。目前完整的响应发送到两个视图。
【问题讨论】:
-
"...只有关联的视图发生了变化。" - 你必须澄清这一点,集合中的某些模型是否与某些视图相关?是什么让一种视图在处理集合的方式上与另一种不同?
-
我会更新问题
-
如果你的响应没有返回一个数组,你应该使用
Backbone.Model而不是Backbone.Collection,然后你可以在每个视图中监听change:attr事件。 -
那,谢谢:)。您可以将此添加为答案以便我接受吗?