我希望能够搜索backbonejs集合中包含的模型属性。我现在就是这样做的...
wherePartial: function(attrs) {
// this method is really only tolerant of string values. you can't do partial
// matches on objects, but you can compare a list of strings. If you send it a list
// of values; attrs={keyA:[1,2,3],keyB:1}, etc the code will loop through the entire
// attrs obj and look for a match. strings are partially matched and if a list is found
// it's expected that it contains a list of string values. The string values should be considered
// to be like an OR operation in a query. Non-list items are like an AND.
if (_.isEmpty(attrs)) return [];
var matchFound = false;
return this.filter(function(model) {
// this is in the outer for loop so that a function isn't created on each iteration
function listComparator(value, index, list){
return model.get(key).toLowerCase().indexOf(value.toLowerCase()) >= 0;
}
for (var key in attrs) {
if (_.isArray(attrs[key])){
matchFound = _.any(attrs[key],listComparator);
if (matchFound !== true) return false;
} else {
matchFound = model.get(key).toLowerCase().indexOf(attrs[key].toLowerCase()) >= 0;
if (matchFound === false) return false;
}
}
return true;
});
}
假设“C”是一个实例化的集合,这就是我使用它的方式:
姓名:joe(昵称:joe the man 昵称:joe 酷昵称:joey)
在文本框中输入并转换为:
C.wherePartial({name:"joe",nicknames:["joe the man","joe cool","joey"]})
上述方法返回所有名称为 joe 的模型,以及在该范围内,任何名称为 joe 的模型和任何昵称。它适用于我的用途。但是,我真的很想进行不需要键:值模式的搜索。我想在搜索框中执行此操作,例如在网络上使用搜索引擎时。我想过只查看每个模型的每个属性,但是当您拥有大量集合(160k+ 模型)时,这需要一段时间。
过去有没有人遇到过这样的需求?如果是这样,您是如何解决的?我想将搜索保留在客户端上,而不是对后端使用任何 ajax 调用。这样做的原因是整个集合已经加载到客户端。