I’m trying to keep a Backbone.js Collection up-to-date with what’s happening on the server.
My code is similar to the following:
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);
What happens is that when the comments are fetched, refresh
is called, the same comments to the bottom of the CommentListView
—which is what I’d expect from the code above.
What I’d like to know is what’s the best way to “refresh” the view, without loosing any “local state”.
Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.
js. Backbone. js developers usually focus on the front-end aspect of web applications, but also must have basic understanding of some back-end technologies, since their responsibility includes the integration of APIs and resources with front-end elements as provided by the back-end developers and engineers.
Or just use the far simpler addition to backbone's fetch method:
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
:-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With