Reputation: 51
I have the next script:
var Game = Backbone.Model.extend({});
var GamesCollection = Backbone.Collection.extend({
model: Game
});
var games = new GamesCollection();
var portal = new Game({name: 'Tetris', year: '2017'});
games.add(portal);
console.log(games.get(0));
Why does "games.get(0)" return 'undefined'? May be I use get method not in correct way?
Upvotes: 5
Views: 1688
Reputation: 2319
AFAICT get()
on models is for attributes, but in your case you are dealing with a collection, which means get()
is:
"Get a model from a collection, specified by id."
E.g.
collection.get(1); // Get model with id = 1 from collection
Because you haven't supplied an id when you made the new Tetris Game, Backbone will generate one on its own, which is likely not "0".
However in your case at(index)
seems to have been the one you looked for, my answer was just to clearify things.
E.g.
collection.at(0); // Get model at collection index 0
Upvotes: 5