我是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