开发者

how to get model from collection

I have the next script:

var Game = Backbone.Model.extend({});

var GamesCollection = Backbone.Collection.extend({
    model: Game
});

var games = new GamesCollection();

v开发者_JAVA技巧ar 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?


Short and sweet, you need:

games.at(0)

.get is for attributes.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜