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

查看:95
本文介绍了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);
}

这是迅速成为累赘,因为我尝试实施相关的收藏操纵其他技巧,如排序。坦率地说,我的code看起来有点哈克。是否有这样做的一个优雅的方式?

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

父集合保持它的模型,你的任何应用过滤器,并绑定到过滤收集知道什么时候已经发生了变化。在添加内部绑定和删除事件可以让你重新应用过滤器。看到
http://jsfiddle.net/dQr7X/ 了演示。

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

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