过滤多个属性的主干集合

时间:2012-06-23 00:11:38

标签: backbone.js

这是在多个属性上过滤主干集合的好方法:

filterData: function(params) {
    // store original data for clearing filters
    this.originalModels = this.models.slice();
    for (var key in params) {
        var val = params[key];
        // if we are dealing with multiple values in an array
        // i.e. ['ford','bmw','mazda']
        if (typeof val === "object") {
            var union = [];
            for (var k in val) {
                var subval = val[k];
                var matched = _.filter(this.models, function(house) {
                   return house.get(key) == subval; 
                });
                union = union.concat(matched);
            }
            this.models = union;
        } else {
           var results = _.filter(this.models, function(house) {
               return house.get(key) == val;
           });
           this.models = results;
        }
    } // end for
    return this.reset(this.models);
},
clearFilters: function() {
    return this.reset(this.originalModels);
}

我测试了它,它允许我以下列方式过滤集合:

filterParams = {brand:['ford','bmw','mazda'], color:black}

carCollection.filterData(filterParams);

它似乎有用,但我不知道是否有更好的方法来做到这一点。

我测试了Backbone.Collection.where()方法,但如果我想说brand: ['bmw','mazda','ford']

它就不起作用

2 个答案:

答案 0 :(得分:7)

你应该能够使用这样的东西:

filterData: function(params) {
    // store original data for clearing filters
    this.originalModels = this.models.slice();

    _.each(params, function(val, key){
        if (typeof val !== 'object') val = [ val ];
        this.models = _.filter(this.models, function(model){
            return _.indexOf(val, model.get(key)) !== -1;
        }, this);
    }, this);
    return this.reset(this.models);
}

答案 1 :(得分:1)

Backbone.js集合可以访问许多underscore.js方法,包括filter()。

carCollection.reset(carCollection.filter(function(car){
  return $.inArray(car.brand,['ford','bmw','mazda']) && car.color === 'black';
}));

未经测试,但如果您使用jQuery则应该可以使用。如果没有,您可以创建自己的inArray()函数

相关问题