我是Backbone的新手,我对将(对象)JSON数组传递给Backbone集合时发生了什么感到困惑。将JSON数组传递给Backbone Collection时错误的collection.length
我从托管在Google云端硬盘上的电子表格中提取一些JSON。我正在解析这些数据,因为我想在我的集合中使用的实际数据是深深嵌套的。在我的解析函数中,如果我记录了我想要的数组的长度,我得到了157(这是正确的)。然后我将该数组传递给Backbone集合,并且我的集合的长度为1(不正确)。就好像foo.bar.length = 157,但'foo'中只有一个'bar',所以当我将foo.bar传入集合时,它需要foo.bar而不是foo.bar的内容!很困惑。下面
代码...
var table = new TableView();
TableItem = Backbone.Model.extend(),
TableItemCollection = Backbone.Collection.extend({
model : TableItem,
url : 'https://spreadsheets.google.com/feeds/list/0AjbU8ta9j916dFdjSVg3YkNPUUJnWkZSWjBDWmZab3c/1/public/basic?alt=json-in-script',
sync : function(method, model, options) {
var params = _.extend({
type: 'GET',
dataType: 'jsonp',
url: this.url,
processData: false
}, options);
return $.ajax(params);
},
parse : function(resp, xhr) {
console.log(resp.feed.entry.length); // THIS LOGS 157
return resp.feed.entry;
}
}),
TableView = Backbone.View.extend({
initialize : function (options) {
this.collection = new TableItemCollection();
this.collection.on('reset', this.parseResponse, this);
this.collection.fetch({
reset : true,
success : function (model, response, options) {
console.log('OK'); // THIS LOGS 'OK'
},
error : function (model, response, options) {
console.log('ERROR');
}
});
},
parseResponse : function() {
console.log(this.collection.length); // THIS LOGS 1
}
});
“resp.feed.entry”的类型是什么?你确定它是一个数组吗?请注销你的解析方法'console.log(_。isArray(resp.feed.entry))'! – nemesv