我是 Backbone 的新手,我对将 JSON 数组(对象)传递给 Backbone 集合时发生的事情感到非常困惑。
我正在从托管在 Google Drive 上的电子表格中获取一些 JSON。我正在解析该数据,因为我想在我的集合中使用的实际数据是深度嵌套的。在我的解析函数中,如果我记录我想要的数组的长度,我得到 157(这是正确的)。然后我将该数组传递到主干集合中,我的集合的长度为 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
}
} );
最佳答案
如果转储 Google Spreadsheets 返回的其中一项,您会看到数据嵌套在多个对象中,如下所示
{
"id":{"$t":"https://spreadsheets.google.com/feeds/list/..."},
"updated":{"$t":"2013-07-30T12:01:24.000Z"},
"category":[{"scheme":"...","term":"..."}],
"title":{"type":"text","$t":"ACIW"},
"content":{},
"link":[{"rel":"self","type":"application/atom+xml","href":"..."}]
}
在 fiddle 中 http://jsfiddle.net/nikoshr/kHBvY/
请注意 id
属性包装在一个对象中 "id":{"$t":"https://spreadsheets.google.com/feeds/list/0AjbU8ta9j916dFdjSVg3YkNPUUJnWkZSWjBDWmZab3c/1/public/basic/cokwr"}
Backbone 集合不允许重复,重复是根据它们的 id 来确定的。您的所有项目都被视为重复项并折叠成一个。如果您删除 id 或消除歧义,您将获得 157 个项目。例如,
parse : function( resp, xhr ) {
var data = resp.feed.entry, i;
console.log(data.length); // THIS LOGS 157
for (i=data.length-1; i>=0; i--)
data[i].id = data[i].id['$t'];
return data;
}
http://jsfiddle.net/nikoshr/kHBvY/2/演示
您可能必须解开所有属性才能以不拉头发的方式使用它们。
关于javascript - 错误的 collection.length 将 JSON 数组传递给 Backbone Collection 时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17993865/