骨干采集计数器

And*_*rle 6 javascript backbone.js

我有一个收藏女巫可以在后端的一个集合上分页,所以onscroll我很多批次的项目.我知道服务器上的项目数.我正在寻找一种方法来扩展我的所有集合getCounter.我们的想法是最初设置服务器计数器,当用户从集合中添加或删除项目时,计数器会更新.什么是最好的方法呢?

我认为问题是add当我从服务器获取新项目时也会触发该事件.否则我可以绑定到addremove事件.

jev*_*lio 5

您需要控制哪些添加和删除应该计数,哪些不计算.我想到了两种选择.

  1. 沉默不应该与统计所有操作silent:true选项,你的柜台挂钩的add,removereset 事件.这将对集合的一般使用设置一些限制,因为您无法在所有情况下使用它们的事件.

  2. 重写add,remove并且reset 方法接受一个额外的选项,它告诉你的计数器是否应更新或没有.就像是:

    var PaginatedCollection = Backbone.Collection.extend({
    
        initialize: function() {
            this._counter = 0;
        },
    
        add: function(models, options) {
            if(options && options.count)
                this._counter += (_.isArray(models) ? models.length : 1);
            Backbone.Collection.prototype.add.apply(this, arguments);
        },
    
        remove: function(models, options) {
            if(options && options.count)
                this._counter -= (_.isArray(models) ? models.length : 1);
            Backbone.Collection.prototype.remove.apply(this, arguments);         
        },
    
        reset: function(models, options) {
            if(options && options.count)
                this._counter = (_.isArray(models) ? models.length : 0);
            Backbone.Collection.prototype.reset.apply(this, arguments)
        }
    });
    
    Run Code Online (Sandbox Code Playgroud)

    并且count:true当计算添加或删除的项目时,传递选项:

    var SomeCollection = PaginatedCollection.extend({ });
    
    var someCollection = new SomeCollection();
    someCollection.add(model, { count: true });
    someCollection.remove(model, { count: true });
    
    Run Code Online (Sandbox Code Playgroud)

(代码样本未经测试)