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

时间:2013-08-07 19:54:34

标签: javascript backbone.js underscore.js

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

我在想像......

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

编辑对不起,我一定不能解释得很清楚。如果我有一个带属性的集合......

[ 
  { first: 'John', last: 'Doe'}, 
  { first: 'Mary', last: 'Jane'} 
]

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

4 个答案:

答案 0 :(得分: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);
    });;
});

答案 1 :(得分:2)

您无需过滤和比较值。 Backbone有一个内置方法where,它从集合中获取模型的子集。

http://backbonejs.org/#Collection-where

var friends = new Backbone.Collection([
  {name: "Athos",      job: "Musketeer"},
  {name: "Porthos",    job: "Musketeer"},
  {name: "Aramis",     job: "Musketeer"},
  {name: "d'Artagnan", job: "Guard"},
]);

var musketeers = friends.where({job: "Musketeer"});

答案 2 :(得分:1)

您需要model中的collection项,以便任何值v都包含您的搜索文本q。这转化为以下内容。

var q = $('input.search').val();
this.collection.filter(function(model) {
    return _.any(model.values(), function(v) {
        return ~v.indexOf(q);
    });
})

答案 3 :(得分:0)

我使用了这个...不敏感的子字符串匹配,用于我的模型属性的一个子集。

var search = $(e.currentTarget).val().toLowerCase();
this.collection.filter(function(model) {
  return _.some(
    [ model.get('first'), model.get('last') ], 
    function(value) {
      return value.toLowerCase().indexOf(search) != -1;
    });
 });
相关问题