Backbone JS:获取集合 - JSON 响应格式有问题
Backbone JS: Fetching a collection – trouble with JSON response format
我在 Backbone JS 中初始填充集合时遇到一些问题。
开发时 myCollection
没有从服务器获取数据,我只是像这样传入:
app.myCollection.reset([
{ person: 'Sally'},
{ person: 'Peter'},
{ person: 'Paul'},
{ person: 'Wilma'}
]);
执行 console.log(app.myCollection);
显示集合已正确填充,因为它的 length
是 4:
s {length: 4, models: Array[4], _byId: Object}
现在我想从服务器获取数据,响应如下所示:
[
{
"person": "Sally"
},
{
"person": "Peter"
},
{
"person": "Paul"
},
{
"person": "Wilma"
}
]
不幸的是,出了点问题,因为 length
属性现在是 0,尽管我可以在对象中找到数据。
s {length: 0, models: Array[0], _byId: Object}
我是这样做的:
app.myCollection.fetch({reset: true});
对我来说,看起来只有外部数组 "mapped" 进入模型,而不是数组内的每个对象。
我能做些什么来防止这种情况发生?
编辑
正如评论中所建议的,我在响应中包含了一个 "id" 属性。现在,它看起来像这样:
[
{
"id": 1,
"person": "Sally"
},
{
"id": 2,
"person": "Peter"
},
{
"id": 3,
"person": "Paul"
},
{
"id": 4,
"person": "Wilma"
}
]
不幸的是,有些地方仍然不对,因为集合现在看起来像这样:
s {length: 0, models: Array[0], _byId: Object}
_byId: Object
length: 4
models: Array[4]
__proto__: s
所以你看,一个长度是 0,另一个是 4。这会不会是因为我目前只是 link 到一个 json 文件?
获取是异步的,所以当您登录控制台时,可能还没有获取数据?您在获取时使用成功回调函数吗?
app.myCollection.fetch({reset: true},success: function() {console.log(app.myCollection);});
我在 Backbone JS 中初始填充集合时遇到一些问题。
开发时 myCollection
没有从服务器获取数据,我只是像这样传入:
app.myCollection.reset([
{ person: 'Sally'},
{ person: 'Peter'},
{ person: 'Paul'},
{ person: 'Wilma'}
]);
执行 console.log(app.myCollection);
显示集合已正确填充,因为它的 length
是 4:
s {length: 4, models: Array[4], _byId: Object}
现在我想从服务器获取数据,响应如下所示:
[
{
"person": "Sally"
},
{
"person": "Peter"
},
{
"person": "Paul"
},
{
"person": "Wilma"
}
]
不幸的是,出了点问题,因为 length
属性现在是 0,尽管我可以在对象中找到数据。
s {length: 0, models: Array[0], _byId: Object}
我是这样做的:
app.myCollection.fetch({reset: true});
对我来说,看起来只有外部数组 "mapped" 进入模型,而不是数组内的每个对象。
我能做些什么来防止这种情况发生?
编辑 正如评论中所建议的,我在响应中包含了一个 "id" 属性。现在,它看起来像这样:
[
{
"id": 1,
"person": "Sally"
},
{
"id": 2,
"person": "Peter"
},
{
"id": 3,
"person": "Paul"
},
{
"id": 4,
"person": "Wilma"
}
]
不幸的是,有些地方仍然不对,因为集合现在看起来像这样:
s {length: 0, models: Array[0], _byId: Object}
_byId: Object
length: 4
models: Array[4]
__proto__: s
所以你看,一个长度是 0,另一个是 4。这会不会是因为我目前只是 link 到一个 json 文件?
获取是异步的,所以当您登录控制台时,可能还没有获取数据?您在获取时使用成功回调函数吗?
app.myCollection.fetch({reset: true},success: function() {console.log(app.myCollection);});