I am trying to transfer my collection of models in Backbone.js to a template. Every time I try to access models (i.e. This.collection.models), I just get an empty array, although I know that the collection contains two models of type Contact. I'm sure something is missing from me. What is the standard way to transfer models to Backbone.js templates?
The following are the definitions of the model, collection, and view (the actual view is called from the Backbone.js router function - the source code for the router is not included 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>
source
share