搜索集合和检索模型backbonejs [英] Search collection and retrieve model backbonejs
问题描述
我试图寻找一个集合的模型属性,然后抓住并返回整个模式?
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: ''
}
});
我收藏有大约myModels 100。
My collection has around 100 of myModels.
我想通过通过收集来搜索
,找到它,然后返回的整个基于myModel
A
这样我就可以访问其他属性?
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 ?
推荐答案
如果我正确地理解你的问题,你要使用的骨干集合在其中,
方法,在这里文档:
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
因此,考虑到MyCollection的名为MyCollection的实例有MyModels在里面,你可以说:
So, given an instance of MyCollection called myCollection that has MyModels in it, you can say:
var foundModels = myCollection.where({a:'some value'});
和 foundModels
将包含你所寻求的车型阵列
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'));
});
这篇关于搜索集合和检索模型backbonejs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!