如何从集合中获取模型
我有下一个脚本:
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));
为什么“games.get(0)”返回“未定义”? 我可能没有以正确的方式使用 get 方法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简短而甜蜜,您需要:
.get
用于属性。Short and sweet, you need:
.get
is for attributes.模型上的 AFAICT
get()
用于属性,但在您的情况下,您正在处理一个集合,这意味着get()
是:“从集合中获取模型,由 id 指定。”
例如
,因为您在制作新的俄罗斯方块游戏时没有提供 id,所以 Backbone 会自行生成一个 id,该 id 可能不是“0”。
然而,在你的情况下
at(index)
似乎就是你要找的那个,我的回答只是为了澄清事情。例如
AFAICT
get()
on models is for attributes, but in your case you are dealing with a collection, which meansget()
is:"Get a model from a collection, specified by id."
E.g.
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.