Backbone.js を Handlebars.js と共に使用して、カスタム JSON API を使用して表示しようとしています。
データは確実に消費され、コレクションに追加されます。
テンプレートはレンダリングされますが、テーブルにはデータがありません (1 行が完全に空)。
これをデバッグするにはどうすればよいですか?
ルーター
'showStatement': function() {
new app.StatementView({collection: new app.StatementCollection()});
}
コレクション
app.StatementCollection = Backbone.Collection.extend({
model: app.Transaction,
url: 'http://localhost/api/public/out/123456/statement',
initialize: function() {
console.log('Init app.StatementCollection');
}
});
モデル
app.Transaction = Backbone.Model.extend({
/*
defaults: {
vendor: 'Unknown',
amount: 'Unknown',
currency: 'Unknown',
date: 'Unknown'
}
*/
});
意見
app.StatementView = Backbone.View.extend({
el: '#page',
template: Handlebars.getTemplate( 'account_statement' ),
initialize: function() {
console.info(this.collection);
this.render();
this.listenTo(this.collection, 'add', this.render);
this.listenTo(this.collection, 'reset', this.render);
this.collection.fetch();
},
// render library by rendering each book in its collection
render: function() {
this.$el.html( this.template( JSON.stringify(this.collection.toJSON())) ); // <------ pretty sure the problem lies here?!?
console.log('col', JSON.stringify(this.collection.toJSON()) ); // <------ the output from this is shown at the bottom
return this;
}
});
ハンドルバー テンプレート
{{#if statement}}
<h1>Your Statement</h1>
<table border="1">
<thead>
<th>Date</th>
<th>Name</th>
<th>Amount</th>
</thead>
<tbody>
{{#each statement}}
{{debug}}
<tr>
<td>{{this.vendor}}</td>
<td>{{currency this.currency}}{{this.amount}}</td>
<td><time class="format-date" datetime="{{this.date}}">{{this.date}}<time></td>
</tr>
{{/each}}
</tbody>
</table>
{{else}}
<p class="warning">Sorry, nothing to show.</p>
{{/if}}
これは、私の API の JSON がどのように見えるかです:
{"status":true,"result":[{"id":1,"vendor":"Jessops","amount":595.99,"currency":"GBP","date":"2012-11-01 04:57:04"},{"id":2,"vendor":"Starbucks","amount":6.99,"currency":"GBP","date":"2012-11-02 04:57:04"},{"id":3,"vendor":"Superdry","amount":155.99,"currency":"GBP","date":"2012-11-03 04:57:04"},{"id":6,"vendor":"Reebok Outlet","amount":205.99,"currency":"USD","date":"2012-11-05 04:57:04"}]}
console.log('col', JSON.stringify(this.collection.toJSON()) ); からの出力
col [{"status":true,"result":[{"id":1,"vendor":"Jessops","amount":595.99,"currency":"GBP","date":"2012-11-01 04:57:04"},{"id":2,"vendor":"Starbucks","amount":6.99,"currency":"GBP","date":"2012-11-02 04:57:04"},{"id":3,"vendor":"Superdry","amount":155.99,"currency":"GBP","date":"2012-11-03 04:57:04"},{"id":6,"vendor":"Reebok Outlet","amount":205.99,"currency":"USD","date":"2012-11-05 04:57:04"}]}]
編集: レンダー関数を次のように変更すると、次のように機能することがわかりました。
render: function() {
data = this.collection.toJSON();
this.$el.html(this.template( {statement: data[0]} ));
return this;
}
これは、私の JSON 出力が間違っていることを示唆しています。の必要性を減らすために JSON を改善するにはどうすればよい[0]
ですか?