在Backbone.js中按子串过滤收集

sav*_*ger 3 javascript backbone.js underscore.js

如果我想为一个集合做一个自动完成,那么最好的方法是什么?我想看一下搜索字符串是否在我的模型中的任何(或少数几个)属性中.

我在想像......

this.collection.filter(function(model) {
    return model.values().contains($('input.search]').val());
})
Run Code Online (Sandbox Code Playgroud)

编辑对不起,我一定不能解释得那么好.如果我有一个带属性的集合......

[ 
  { first: 'John', last: 'Doe'}, 
  { first: 'Mary', last: 'Jane'} 
]
Run Code Online (Sandbox Code Playgroud)

我想输入a我的搜索,捕获keyup事件,并过滤掉{ first: 'Mary', last: 'Jane'},因为John和Doe都不包含a.

jcr*_*898 9

你可以看看模型attributes做这样的事情......

var search = $('input.search]').val();
this.collection.filter(function(model) {
    return _.any(model.attributes, function(val, attr) {
        // do your comparison of the value here, whatever you need
        return ~val.indexOf(search);
    });;
});
Run Code Online (Sandbox Code Playgroud)