Я пытаюсь сохранить коллекцию 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
, что и ожидал от кода выше.
Какой идентификатор должен знать, это лучший способ "обновить" представление, не теряя "локального состояния".