Backbone.jsのモデルのコレクションをテンプレートに渡すのに苦労しています。モデル(つまりthis.collection.models)にアクセスしようとするたびに、コレクションにContactタイプの2つのモデルが含まれていることがわかっていても、空の配列が取得されます。私はここで基本的な何かが欠けていると確信しています。モデルをBackbone.jsテンプレートに渡す標準的な方法は何ですか?
以下は、モデル、コレクション、およびビューの定義です(実際のビューは、Backbone.jsルーター関数内から呼び出されます。ルーターのソースコードは、簡潔にするためにここには含まれていません)。
var Contact = Backbone.Model.extend({
urlRoot: '/contacts.json',
idAttribute: '_id',
parse: function(response) {
return response;
}
});
var Contacts = Backbone.Collection.extend({
model: Contact,
url: '/contacts.json',
parse: function(response) {
return response.data;
}
});
var ListContactsView = Backbone.View.extend({
el: $('#content'),
template: _.template($('#list-contacts-tpl').html()),
initialize: function() {
this.collection = new Contacts();
this.collection.fetch();
this.render();
},
render: function() {
console.log(this.collection);
this.$el.html(this.template({ contacts: this.collection.models }));
}
});
テンプレートは次のように定義されています。
<script id="list-contacts-tpl" type="text/template">
<% console.log(contacts); %>
</script>