0

I am trying to pull in a collection from the url attribute and am having some problems. It seems fetch() returns successfully, but then I cannot access the models in my collection with get(). I am using bbb and requireJS to develop my modules

var rooms = new Rooms.Collection(); // calls the rooms module
  rooms.fetch({success: function(){
      console.log(rooms.get(1)); // should output the first model
});

Here is my collection code in the rooms module:

Rooms.Collection = Backbone.Collection.extend({
    model: Rooms.Model,
    url: 'http://localhost:8888/projects/meeting-room/app/data/rooms.json'
});

If I output rooms, everything turns out fine. But when I try for a specific model, that is when I get an error.

[{
    "id": 12345,
    "name": "Ford",
    "occupied": false
},
{
    "id": 23458,
    "name": "Chevy",
    "occupied": false
},
{
    "id": 83565,
    "name": "Honda",
    "occupied": false
}]
Jeff
  • 2,293
  • 4
  • 26
  • 43

1 Answers1

2

The collection.get method looks up a model by id. If you want to find a model by position, use collection.at instead.

Also notice that array indices in javascript are 0-based, so the first model can be found with:

var model = collection.at(0); 

For convenience, Backbone collections also implement some of underscore's array and collection methods, including first. That means you can also find the first model with:

var model = collection.first();
jevakallio
  • 35,324
  • 3
  • 105
  • 112
  • Nitpicking, feel free to ignore me :) `collection.get` supports lookup by both id and cid since 0.9.9 (and replaces getByCid) – nikoshr Jan 29 '13 at 16:37
  • @nikoshr, so it does, but I didn't feel it was relevant to mention here. Shall your comment document this fact for visitors from the future. – jevakallio Jan 29 '13 at 16:38
  • collection.get(cid) definitely did not work for me. When I used the id attribute, it worked. Using collection.at(cid) also worked. – Jeff Jan 29 '13 at 16:48
  • @Jeff, `.get(cid)` oughta work, `.at(cid)` might work by coincidence if `cid === index`. Are you using `>=0.9.9`? – jevakallio Jan 29 '13 at 16:57
  • Backbone.js 0.9.2. When I ran 'bbb init' that is what it gave me. – Jeff Jan 29 '13 at 20:31
  • @Jeff, as nikoshr mentions in his initial comment, the cid lookup functionality was added to `collection.get` only in v0.9.9. Before that we had `collection.getByCid`. – jevakallio Jan 29 '13 at 20:33