轮询Backbone.js的集合 [英] Polling a Collection with Backbone.js

查看:153
本文介绍了轮询Backbone.js的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图保持Backbone.js的集合了最新当今发生的事情在服务器上。

I’m trying to keep a Backbone.js Collection up-to-date with what’s happening on the server.

我的code是类似以下内容:

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);

什么情况是,当评论有牵强,刷新被称为,同样意见的底部 CommentListView 首位,而其正是我所期待的code以上。

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

推荐答案

你想要做的就是刷新集合每隔几秒钟,并追加新的注释。我的建议是处理你的后端了这个问题。发送过去的时间戳从你最后的评论,并要求服务器仅此日期增量。

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");
  }
});

在你的后台,查询数据库基础上,from_time parameter.Your客户端code不改变刷新视图。

In your backend, query your database based on the from_time parameter.Your client code does not change to refresh the view.

如果你不想改变你的后台code因任何原因则addAll功能加入这一行:

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);
} 

这篇关于轮询Backbone.js的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆