Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polling a Collection with Backbone.js

Tags:

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”.

like image 343
sneeu Avatar asked May 11 '11 11:05

sneeu


People also ask

Do people still use Backbone JS?

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.

Is Backbone JS frontend or backend?

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.


1 Answers

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

:-)

like image 107
Jason Stonebraker Avatar answered Jan 22 '23 23:01

Jason Stonebraker