私はバックボーンを初めて使用し、(オブジェクトの) JSON 配列をバックボーン コレクションに渡すときに何が起こっているのかについて非常に混乱しています。
Google ドライブでホストされているスプレッドシートから JSON を取得しています。コレクションで使用したい実際のデータは深くネストされているため、そのデータを解析しています。私の解析関数で、目的の配列の長さをログに記録すると、157 になります (これは正しいです)。次に、その配列をバックボーン コレクションに渡します。コレクションの長さは 1 (正しくありません) です。foo.bar.length = 157 のようですが、「foo」には「bar」が 1 つしかないため、コレクションに 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
}
} );