我试图通过它的ID从集合中获取模型并在视图中显示。在实例化模型后,我使用get()
,at()
等方法,但它返回undefined
。
我的收藏:
[
{
"id": "1",
"firstname": "Abc",
"lastname": "Xyz"
},
{
"id": "2",
"firstname": "Klm",
"lastname": "Opq"
},
{
"id": "2",
"firstname": "rst",
"lastname": "Yvw"
}
]
实例化:
var persons = new PersonCollection();
console.log(persons.get(1)); // undefined
注意:我在控制台中获取所有模型(不是问题)。我只想通过它的id名称来获取模型。
答案 0 :(得分:1)
fetch
是异步的,因此您需要将代码置于成功回调
persons.fetch({
success: function() {
console.log('Now I have something: ', persons.get(1))
}
})
console.log('Nothing here: ', persons.get(1))
BTW要按ID获取单个模型,您可以使用Model#fetch
代替