2014-01-24 109 views
0

我想通过它的id在主干中的集合中找到一个模型。如何通过id找到骨干网中的骨干模型?

下面是一个示例代码:

model = Backbone.Model.extend({ 
}); 
collection = Backbone.Collection.extend({ 
model:model, 
url:url, 
}); 
myCollection = new collection(); 
myCollection.fetch(); 
myCollection.find({id:2}).toJSON(); 

我想找到一个特定ID的模式,但它不喜欢这个工作?

我认为问题在于我无法正确使用find()

我应该怎么做?

回答

2

什么你要找的是

myCollection.where({id:2})[0].toJSON(); 

看到http://underscorejs.org/#where

实际查找需要一个函数作为参数(http://underscorejs.org/#find

+0

'where'返回的数组不是对象,所以'.toJSON()'不起作用。 'myCollection.where({id:2})[0] .toJSON();'是正确的形式。 @david_sulc – RedHood148

+0

糟糕,更新了我的答案! –