documentcloud/backbone — Issue #708: Backbone.Collection.get(id) randomly returns with undefined
Author: korsosm
Created: 2011-11-01 04:11:10+00:00
State: open

Hey,

I've spent some time figuring out what is not working in my code, and realized that the Backbone.Collection.get(id) sometimes returned randomly with undefined. Finally I'm using Backbone.Collection.at(index), that is the proper way to solve my problem, but hopefully this issue helps you guys make Backbone.js more better.

I'm writing an image viewer app, so I set up three collections. One for the current item, one for the upcoming items and one hidden for buffering some images, all of them has only 5-10 models. The thing that i want to do is to get the first element from a collection (this) to pass it to another collection.

```javascript
var Items = Backbone.Collection.extend({
model: Item,
getItem: function() {
// returns and removes the first item from this collection
if (this.length) {
var firstItemId = this.toJSON()[0].id;
itemToReturn = this.get(firstItemId);
this.remove(itemToReturn);
return itemToReturn;
} else {
qbConsole.log('No more items in '+this.name+'.');
return false;
}
}
});
```

So in this code, itemToReturn have sometimes randomly undefined, even the Collection has the model with the specified ID, that is the only model with this ID, and ID is integer in the model (when it was string it breaks more frequently - but thats not a surprise).

milan