3
votes

I am struggling to pass my collection of models in Backbone.js into the template. Everytime I attempt to access the models (i.e. this.collection.models) I just get an empty array even though I know the collection contains two models of type Contact. I am sure I am missing something basic here. What is the standard way of passing models to Backbone.js templates?

Following is the model, collection and view definitions (the actual view is called from within a Backbone.js router function - source code for router not include here for brevity):

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 }));
  }
});

The template is defined as follows:

<script id="list-contacts-tpl" type="text/template">
  <% console.log(contacts); %> 
</script>
1

1 Answers

6
votes

If your code is truly as shown in your question, the issue is that you are rendering the view before the fetch has returned, which is why your collection is empty. The fetch takes time to return, but you're calling render immediately after calling fetch.

Either call render in the success handler of the fetch function, or bind render to the reset event of the collection.