如何从集合中获取模型

and*_*nd1 5 javascript backbone.js

我有下一个脚本:

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));
Run Code Online (Sandbox Code Playgroud)

为什么"games.get(0)"返回'undefined'?可能是我用get方法不正确吗?

小智 8

简短而甜蜜,你需要:

games.at(0)
Run Code Online (Sandbox Code Playgroud)

.get 是为了属性.


ein*_*bst 5

get()模型上的AFAICT 用于属性,但在您的情况下,您正在处理集合,这意味着get():

"从ID指定的集合中获取模型."

例如

collection.get(1); // Get model with id = 1 from collection
Run Code Online (Sandbox Code Playgroud)

因为你在制作新的俄罗斯方块游戏时没有提供id,所以Backbone会自己生成一个,这可能不是"0".

但是在你的情况下at(index)似乎是你所寻找的那个,我的回答只是为了澄清事情.

例如

collection.at(0); // Get model at collection index 0
Run Code Online (Sandbox Code Playgroud)