Backbone.js:过滤集合的正确方法? [英] Backbone.js: correct way of filtering a collection?

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

问题描述

我目前使用的方法是过滤一个集合,它返回一个数组,然后使用

The current method I'm using is to filter a collection, which returns an array, and use

collection.reset(array)

重新填充它.但是,这会修改原始集合,因此我添加了一个名为originalCollectionArray"的数组,它跟踪集合的初始数组状态.当没有过滤处于活动状态时,我只是使用

to re-populate it. However, this modifies the original collection, so I added an array called "originalCollectionArray" which keeps track of the initial array state of the collection. When no filtering is active I simply use

collection.reset(originalCollectionArray)

但是,我需要跟踪从真实集合中添加和删除模型,所以我这样做了:

But then, I need to keep track of adding and removing models from the real collection, so I did this:

// inside collection
initialize: function(params){
    this.originalCollectionArray = params;
    this.on('add', this.addInOriginal, this);
    this.on('remove', this.removeInOriginal, this);
},
addInOriginal: function(model){
    this.originalCollectionArray.push(model.attributes);
},
removeInOriginal: function(model){
    this.originalTasks = _(this.originalTasks).reject(function(val){
        return val.id == model.get('id');
    });
},
filterBy: function(params){
    this.reset(this.originalCollectionArray, {silent: true});
    var filteredColl = this.filter(function(item){
        // filter code...
    });
    this.reset(filteredColl);
}

当我尝试实现与集合操作相关的其他技巧时,这很快变得很麻烦,例如排序.坦率地说,我的代码看起来有点 hacky.有没有一种优雅的方式来做到这一点?

This is quickly becoming cumbersome as I try to implement other tricks related to the manipulation of the collection, such as sorting. And frankly, my code looks a bit hacky. Is there an elegant way of doing this?

谢谢

推荐答案

您可以创建一个集合作为反映过滤器状态的主集合的属性:

You could create a collection as a property of the main collection reflecting the state of the filters:

var C = Backbone.Collection.extend({
    initialize: function (models) {
        this.filtered = new Backbone.Collection(models);
        this.on('add', this.refilter);
        this.on('remove', this.refilter);
    },

    filterBy: function (params){
        var filteredColl = this.filter(function(item){
          // ...
        });

        this.filtered.params = params;
        this.filtered.reset(filteredColl);
    },

    refilter: function() {
        this.filterBy(this.filtered.params);
    }
});

无论您应用什么过滤器,父集合都会保留其模型,并且您绑定到过滤后的集合以了解何时发生更改.在 add 和 remove 事件内部绑定允许您重新应用过滤器.看http://jsfiddle.net/dQr7X/ 进行演示.

The parent collection keeps its models whatever filters you applied, and you bind to the filtered collection to know when a change has occurred. Binding internally on the add and remove events lets you reapply the filter. See http://jsfiddle.net/dQr7X/ for a demo.

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

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