3

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>
4

1 に答える 1

6

コードが本当に質問に示されているとおりである場合、問題は、fetchが戻る前にビューをレンダリングしていることです。これが、コレクションが空である理由です。fetch戻るには時間がかかりますが、を呼び出したrender直後に呼び出していfetchます。

render関数の成功ハンドラーを呼び出すか、コレクションのイベントにfetchバインドrenderします。reset

于 2012-05-22T12:15:43.797 に答える