gpt4 book ai didi

backbone.js - 过滤多个属性的主干集合

转载 作者:行者123 更新时间:2023-12-04 23:27:02 24 4
gpt4 key购买 nike

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

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'] 就行不通了

最佳答案

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

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

关于backbone.js - 过滤多个属性的主干集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11165660/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com