Reputation: 439
I want to find a model by its id in a collection in backbone.
Here's a sample code:
model = Backbone.Model.extend({
});
collection = Backbone.Collection.extend({
model:model,
url:url,
});
myCollection = new collection();
myCollection.fetch();
myCollection.find({id:2}).toJSON();
I want to find the model with a specific id but it doesn't work like this?
I thinks the problem is that I can't use find()
correctly.
How should I do it?
Upvotes: 0
Views: 155
Reputation: 7692
Backbone already has a built in method to do this Collection.get(id)
Upvotes: 0
Reputation: 25994
What you're looking for is
myCollection.where({id:2})[0].toJSON();
see http://underscorejs.org/#where
Find actually takes a function as an argument (http://underscorejs.org/#find)
Upvotes: 2