0

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;

man
  • 498
  • 5
  • 12

2 Answers2

0

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
develoser
  • 128
  • 2
  • 5
0

It seems like you're trying to ascribe attributes to a collection, but a collection is merely a set of models. Having additional data that is constant throughout the collection suggests that it should be wrapped inside another Model, which is demonstrated here: Persisting & loading metadata in a backbone.js collection

Community
  • 1
  • 1
Zach
  • 61
  • 5