Filter Collection by Substring in Backbone.js

Filter Collection by Substring in Backbone.js

本文关键字:Backbone js in Substring Collection by Filter      更新时间:2023-09-26

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

我在想。。。

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

您可以查看模型的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);
    });;
});

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

http://backbonejs.org/#Collection-其中

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

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

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

我用了这个。。。不区分大小写,为我的模型属性的子集匹配子字符串。

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