我试图使用一个集合生成多个视图,每5秒提取一次。
下面是一个工作示例,但两个视图在获取时都会刷新。我可以将响应连接到多个urls中,但我希望将请求的数量降到最低。
我当前的问题是,当集合被重取时,我不希望所有视图每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‘不应该重新呈现。目前,对这两个视图都发送了完整的响应。
发布于 2017-03-01 15:08:39
当处理返回对象而不是对象数组的API时,最好的方法是直接使用Backbone.Model。
update: function () {
let self = this;
this.model.fetch({
update: true, remove: false, success: function () {
setTimeout(self.update, 5000);
}
});
}模型仍然以与集合相同的方式获取,但是视图可以侦听模型上的特定属性,而不是:
this.collection.bind('sync', this.render, this);可以使用以下方法:
this.model.bind('change:json-1', this.render, this);提示:更适合于listenTo而不是绑定,它更安全(参见文档)
this.listenTo(this.model, 'change:json-1', this.render);https://stackoverflow.com/questions/42534329
复制相似问题