使用Backbone.js对集合进行轮询

23

我正在尝试使一个Backbone.js集合与服务器上发生的情况保持同步。

我的代码类似于以下内容:

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

当获取评论时,会调用refresh函数,这会使得相同的评论显示在CommentListView的底部——这是我从上面的代码中所期望的。

我想知道最好的“刷新”视图的方法,而不会丢失任何“本地状态”。

4个回答

31

或者只需使用更简单的方式将添加到backbone的fetch方法中:

this.fetch({ update: true });

当模型数据从服务器返回时,集合将被(高效地)重置,除非您传递 {update: true},在这种情况下,它将使用更新来(智能地)合并获取的模型。- Backbone文档

:-)


16

你想要做的是每隔几秒钟刷新集合并追加新评论。我的建议是在后端解决这个问题。发送你最后一条评论的时间戳,并且只请求从该日期开始的增量数据。

为了做到这一点,在你的集合中:

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参数查询你的数据库。你的客户端代码不需要更改以刷新视图。

如果由于任何原因您不想更改后端代码,请在addAll函数中添加此行:

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

8

Backbone.Collection.merge([options])

在 @Jeb 的回答基础上,我将此行为封装成了一个 Backbone 扩展,您可以复制并粘贴到 .js 文件中,并在页面中包含它(在包含 Backbone 库本身之后)。

它提供了一个名为 merge 的方法,用于 Backbone.Collection 对象。与 fetch 不同,它不完全重置现有的集合,而是比较服务器响应和现有集合之间的差异进行合并。

  1. 它会向现有集合中添加在响应中出现但不存在于现有集合中的模型。
  2. 它会从现有集合中删除响应中没有的模型。
  3. 最后,它会更新现有集合中且在响应中也存在的模型的属性。

所有预期的事件都将被触发,用于添加、删除和更新模型。

选项哈希包含 successerror 回调函数,这些函数将作为参数传递给 (collection, response),并提供了第三个回调选项 complete,无论成功还是失败都将执行它(对于轮询场景非常有帮助)。

它会触发名为 "merge:success" 和 "merge:error" 的事件。

下面是扩展内容:

// Backbone Collection Extensions
// ---------------

// Extend the Collection type with a "merge" method to update a collection 
// of models without doing a full reset.

Backbone.Collection.prototype.merge = function(callbacks) {
    // Make a new collection of the type of the parameter 
    // collection.
    var me = this;
    var newCollection = new me.constructor(me.models, me.options);
    this.success = function() { };
    this.error = function() { };
    this.complete = function() { };

    // Set up any callbacks that were provided
    if(callbacks != undefined) {
        if(callbacks.success != undefined) {
            me.success = callbacks.success;
        }

        if(callbacks.error != undefined) {
            me.error =  callbacks.error;
        }

        if(callbacks.complete != undefined) {
            me.complete = callbacks.complete;
        }
    }

    // Assign it the model and url of collection.
    newCollection.url = me.url;
    newCollection.model = me.model;

    // Call fetch on the new collection.
    return newCollection.fetch({
        success: function(model, response) {
            // Calc the deltas between the new and original collections.
            var modelIds = me.getIdsOfModels(me.models);
            var newModelIds = me.getIdsOfModels(newCollection.models);

            // If an activity is found in the new collection that isn't in
            // the existing one, then add it to the existing collection.
            _(newCollection.models).each(function(activity) {
                if (_.indexOf(modelIds, activity.id) == -1) { 
                    me.add(activity);
                }
            }, me);

            // If an activity in the existing collection isn't found in the
            // new one, remove it from the existing collection.
            var modelsToBeRemoved = new Array();
            _(me.models).each(function(activity) {
                if (_.indexOf(newModelIds, activity.id) == -1) {  
                    modelsToBeRemoved.push(activity);
                }
            }, me);
            if(modelsToBeRemoved.length > 0) {
                for(var i in modelsToBeRemoved) {
                    me.remove(modelsToBeRemoved[i]);
                }
            }

            // If an activity in the existing collection is found in the
            // new one, update the existing collection.
            _(me.models).each(function(activity) {
                if (_.indexOf(newModelIds, activity.id) != -1) { 
                    activity.set(newCollection.get(activity.id));  
                }
            }, me);

            me.trigger("merge:success");

            me.success(model, response);
            me.complete();
        },
        error: function(model, response) {
            me.trigger("merge:error");

            me.error(model, response);
            me.complete();
        }
    });
};

Backbone.Collection.prototype.getIdsOfModels = function(models) {
        return _(models).map(function(model) { return model.id; });
};

简单使用场景:

var MyCollection = Backbone.Collection.extend({
  ...
});
var collection = new MyCollection();
collection.merge();

错误处理使用场景:


var MyCollection = Backbone.Collection.extend({
  ...
});

var collection = new MyCollection();

var jqXHR = collection.merge({
    success: function(model, response) {
        console.log("Merge succeeded...");
    },
    error: function(model, response) {
        console.log("Merge failed...");
        handleError(response);
    },
    complete: function() {
        console.log("Merge attempt complete...");
    }
});

function handleError(jqXHR) {
    console.log(jqXHR.statusText);

    // Direct the user to the login page if the session expires
    if(jqXHR.statusText == 'Unauthorized') {
        window.location.href = "/login";                        
    }
};

现在有一种更简单的方法来处理这个问题,只需设置fetch()方法的更新选项参数即可。请参见我的其他答案。 - Jason Stonebraker

3
制作一个复制集合。Fetch()它。比较两者以找到差异。应用它们。
      /*
       * Update a collection using the changes from previous fetch,
       * but without actually performing a fetch on the target 
       * collection. 
       */
      updateUsingDeltas: function(collection) {
        // Make a new collection of the type of the parameter 
        // collection.
        var newCollection = new collection.constructor(); 

        // Assign it the model and url of collection.
        newCollection.url = collection.url;
        newCollection.model = collection.model;

        // Call fetch on the new collection.
        var that = this;
        newCollection.fetch({
          success: function() {
            // Calc the deltas between the new and original collections.
            var modelIds = that.getIdsOfModels(collection.models);
            var newModelIds = that.getIdsOfModels(newCollection.models);

            // If an activity is found in the new collection that isn't in
            // the existing one, then add it to the existing collection.
            _(newCollection.models).each(function(activity) {
              if (modelIds.indexOf(activity.id) == -1) { 
                collection.add(activity);
              }
            }, that);

            // If an activity in the existing colleciton isn't found in the
            // new one, remove it from the existing collection.
            _(collection.models).each(function(activity) {
              if (newModelIds.indexOf(activity.id) == -1) {  
                collection.remove(activity);  
              }
            }, that);

            // TODO compare the models that are found in both collections,
            // but have changed. Maybe just jsonify them and string or md5
            // compare.
          }
        });
      },

      getIdsOfModels: function(models) {
        return _(models).map(function(model) { return model.id; });
      },

优秀的解决方案。我一直在尝试在collection.parse方法中完成它,但一无所获。我真的希望这种行为能够被添加到Backbone API中。不管怎样,这是我的TODO项目更新现有模型的实现。_(collection.models).each(function(activity) { if (newModelIds.indexOf(activity.id) != -1) { activity.set(newCollection.get(activity.id)); } }, that); - Jason Stonebraker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接