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>