简体   繁体   English

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

[英]Filter Collection by Substring in Backbone.js

If I were to want to do an autocomplete for a collection, what would be the best way? 如果我想为一个集合做一个自动完成,那么最好的方法是什么? I'd like to see if a search string is in any (or a select few) attributes in my model. 我想看一下搜索字符串是否在我的模型中的任何(或少数几个)属性中。

I was thinking something like... 我在想像......

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

Edit I'm sorry, I must not have explained it well enough. 编辑对不起,我一定不能解释得那么好。 If I have a collection with attributes... 如果我有一个带属性的集合......

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

I want to type in a into my search, catch the keyup event, and filter out { first: 'Mary', last: 'Jane'} , as neither John nor Doe contains an a . 我想在我的搜索中键入a ,捕获keyup事件,并过滤掉{ first: 'Mary', last: 'Jane'} ,因为John和Doe都不包含a

You can look at the model's attributes to do something like this... 您可以查看模型的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);
    });;
});

You do not need to filter and compare values. 您不需要过滤和比较值。 Backbone has an inbuilt method where which fetches a subset of models from the collection. Backbone有一个内置方法where从集合中获取模型的子集。

http://backbonejs.org/#Collection-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"});

You want model items in your collection such that any of the values v contain your search text q . 您需要collection model项,以使任何值v包含您的搜索文本q That translates to the following. 这转化为以下内容。

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

I went with this... case insensitive, substring matching for a subset of my model attributes. 我使用了这个...不区分大小写,子串匹配我的模型属性的子集。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM