我正嘗試使用一個集合和一個每5秒獲取一次來生成多個視圖。Backbone.js多個視圖,一個集合,一個提取
下面是一個工作示例,但兩個視圖都在刷新時刷新。 我可以將響應拼接到多個網址,但我想最大限度地減少請求的數量。
我目前的問題是,我不希望所有的視圖重新渲染時,每集合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'不應該重新呈現。目前完整的回覆將發送到兩個視圖。
「...只有關聯的視圖發生了變化」。 - 您必須澄清這一點,集合中的某些模型是否與某些視圖有關?是什麼使得一個視圖在與集合的工作方式上有所不同? – mikeapr4
我會更新問題 – coop
如果你的回答沒有返回數組,你應該使用'Backbone.Model'而不是'Backbone.Collection',然後你可以在每個視圖中監聽'change:attr'事件。 – mikeapr4