admin管理员组文章数量:1278948
If I were to want to do an autoplete 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
.
If I were to want to do an autoplete 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
.
4 Answers
Reset to default 9You can look at the model's attributes
to do something like this...
var search = $('input.search]').val();
this.collection.filter(function(model) {
return _.any(model.attributes, function(val, attr) {
// do your parison of the value here, whatever you need
return ~val.indexOf(search);
});;
});
You do not need to filter and pare values. Backbone has an inbuilt method where
which fetches a subset of models from the collection.
http://backbonejs/#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
. 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;
});
});
本文标签: javascriptFilter Collection by Substring in BackbonejsStack Overflow
版权声明:本文标题:javascript - Filter Collection by Substring in Backbone.js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741224892a2361672.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论