Polling a Collection with Backbone.js

前端 未结 4 413
温柔的废话
温柔的废话 2021-01-30 02:49

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


        
4条回答
  •  执笔经年
    2021-01-30 03:15

    What you want to do is refresh the collection every few seconds and append the new comments. My suggestion is to deal with that problem on your backend. Send over the last timestamp from your last comment and ask the server for the delta from this date only.

    To do so, in your 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 your backend, query your database based on the from_time parameter.Your client code does not change to refresh the view.

    If you do not want to change your backend code for any reason add this line in the addAll function:

    addAll: function(){
      $(this.el).empty();
      this.collection.each(this.addOne);
    } 
    

提交回复
热议问题