javascript - Polling a Collection with Backbone.js -


i’m trying keep backbone.js collection up-to-date what’s happening on server.

my code similar 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 when comments fetched, refresh called, same comments bottom of commentlistview—which i’d expect code above.

what i’d know what’s best way “refresh” view, without loosing “local state”.

what want refresh collection every few seconds , append new comments. suggestion deal problem on backend. send on last timestamp last comment , ask server delta date only.

to so, in collection:

commentcollection = backbone.collection.extend({   url: function(){     return "/comments?from_time=" + this.last().get("created_at");   },   comparator: function(comment){     return comment.get("created_at");   } }); 

in backend, query database based on from_time parameter.your client code not change refresh view.

if not want change backend code reason add line in addall function:

addall: function(){   $(this.el).empty();   this.collection.each(this.addone); }  

Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -