RedHood148
RedHood148

Reputation: 439

How to find a backbone model inside a backbone collection by id?

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

Answers (2)

kay.one
kay.one

Reputation: 7692

Backbone already has a built in method to do this Collection.get(id)

Upvotes: 0

David Sulc
David Sulc

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

Related Questions