问题
I am trying to search a collection for a model attribute and then grab and return the entire model ?
var myModel = Backbone.Model.extend({
defaults: {
a: '',
b: '',
c: '',
d: '',
e: ''
}
});
My collection has around 100 of myModels.
I am trying to search through the collection by a
, find it and then return the entire myModel
of a
so I can access the other attributes ?
回答1:
If I understand your question correctly, you want to use the where
method on Backbone collections, here in the docs:
http://backbonejs.org/#Collection-where
So, given an instance of MyCollection called myCollection that has MyModels in it, you can say:
var foundModels = myCollection.where({a:'some value'});
and foundModels
will contain an array of the models you seek
BTW, if you are doing a more complex search, use the filter
method instead, passing a function as the first argument that returns true on the desired match:
var modelsWhoseAStartsWithA = myCollection.filter(function(anyModel) {
var startsWithA = new RegExp(/^[aA]/);
return startsWithA.test(anyModel.get('a'));
});
来源:https://stackoverflow.com/questions/14450011/search-collection-and-retrieve-model-backbonejs