How do I get a model from a Backbone.js collection by its id?

64,522

Solution 1

Take a look at the get method, it may be of some help :)

http://backbonejs.org/#Collection-get

get collection.get(id)
Get a model from a collection, specified by an id, a cid, or by passing in a model.

Solution 2

If your data requires you to use a different kind of key or a set that doesn't mesh well with at(), getByCid() or get(), there is also where(). Something like this might work:

window.lib = new Library;
window.lib.fetch([
    success: function(model, response) {
        console.log(window.lib.where({'BookID':488, 'Rev':2, 'Status':'Active'});
    }
});
Share:
64,522
Thomas Hunter II
Author by

Thomas Hunter II

I came here to kick ass, build web applications, and chew bubble gum. And I'm all out of gum.

Updated on June 09, 2020

Comments

  • Thomas Hunter II
    Thomas Hunter II almost 4 years

    In my app, everything I do with data is based on the primary key as the data is stored in the database. I would like to grab a model from a collection based on this key.

    Using Collection.at() requires the array index, Collection.getByCid() requires the client ID that backbone randomly generates.

    What is the best way to grab the model I want from the collection with the given id value? I figure the worst I could do would be to iterate over each item, .get('id'), and return that one.

  • DOK
    DOK almost 10 years
    I'll save you a click. The entire documentation there is: Get a model from a collection, specified by an id, a cid, or by passing in a model. var book = library.get(110);