Search code examples
backbone.js

Backbone Collection get property


Got a server returning a JSON object like so:

{
    'key1':'value'
    'key2':{
        'key2_0':'value'
    }
}

And a collection:

var Collection = Backbone.Collection.extend({
    url:api.url//which returns the object above
});
var collection = new Collection();
collection.fetch({
    success:function(data){
        //do something
    }
});

Now i need to use certain properties of the collection throughout my application, but say i need key1, i always have to do collection.at(0).get('key1');//returns 'value', because the data returned is stored within the collection, in a new Array at key 0.

Question:

How to directly... collection.get('key1')//now returns undefined... because it is.

I know i could expose an object to the global scope in the collection success function some_other_var = data.toJSON()[0] and access the some_other_var properties directly, but that's not what i'm looking for;


Solution

  • In order to use the get() function from a Backbone.Collection you need to know the model id or cid wanted.

    For instance, lets say your data coming from the server is like follow:

    [{
    id: '123',
    name: 'Alex'
    }, {
    id: '456',
    name: 'Jhon'
    }]
    

    In that case you can do this:

    this.collection.get('123').get('name') // Return "Alex"
    

    Keep in mind that collection is just a set of model, so behind the scenes by doing collection.get() you are getting a model

    Tip: If you don't have any kind of id in your server data, there is always the option of using underscore methods:

    • find
    • filter
    • some
    • contains
    • etc