我正在尝试使 Backbone.js 集合与服务器上发生的情况保持同步。
我的代码类似于以下内容:
var Comment = Backbone.Model.extend({});
var CommentCollection = Backbone.Collection.extend({
model: Comment
});
var CommentView = Backbone.View.extend({ /* ... */ });
var CommentListView = Backbone.View.extend({
initialize: function () {
_.bindAll(this, 'addOne', 'addAll');
this.collection.bind('add', this.addOne);
this.collection.bind('refresh', this.addAll);
},
addOne: function (item) {
var view = new CommentView({model: item});
$(this.el).append(view.render().el);
},
addAll: function () {
this.collection.each(this.addOne);
}
});
var comments = new CommentCollection;
setInterval(function () {
comments.fetch();
}, 5000);
发生的情况是,当获取评论时,会调用 refresh
,将相同的评论添加到 CommentListView
的底部 - 这就是我所期望的上面的代码。
我想知道什么是“刷新” View 而不丢失任何“本地状态”的最佳方式。
最佳答案
或者只使用 Backbone 的 fetch 方法中更简单的补充:
this.fetch({ update: true });
When the model data returns from the server, the collection will be (efficiently) reset, unless you pass {update: true}, in which case it will use update to (intelligently) merge the fetched models. - Backbone Documentation
:-)
关于javascript - 使用 Backbone.js 轮询集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5963324/