scapegoat17 scapegoat17 - 2 months ago 27
Javascript Question

Backbone - cannot read property 'get' of undefined

This is my first time really trying to create a Backbone application with a server endpoint and I have found myself in a bit of a snag.

I have an underscore template in my html here:

<tbody>
<% _.each(users, function(user) { %>
<tr>
<td><% user.get('firstname') %></td>
<td><% user.get('lastname') %></td>
<td><% user.get('age') %></td>
<td></td>
</tr>
<% }); %>
</tbody>


And I here is my model/view/collection:

var Users = Backbone.Collection.extend({
url: '/UMA.Service/Service1.svc/',
Model: User
});

var User = Backbone.Model.extend({
defaults: {
"firstname": "",
"lastname": "",
"age": null
}
});

var UserList = Backbone.View.extend({
el: '.page',
render: function() {
console.log(this.collection.toJSON());
var template = _.template($('#user-list-template').html(), {users: this.collection.model});
this.$el.html(template);

},
initialize: function() {
var that = this;
this.collection = new Users();
this.collection.fetch({
success: function(User) {
that.render();
}
});

}
});


I am not really sure where I am messing up. I thought that it might have to be how I am calling something in my collection or model but I have looked for a while and cannot find it if there is. Would anyone be able to help me out?

I have my console log in my render function in the view and that returns all of my data so I cannot see why this is not working. Does anyone have any ideas?

Answer

Instead of:

_.each(users, function(user) {...

Try doing:

users.each(function(user) { ...

Backbone "proxys" various underscore methods onto backbone objects (in this case the Collection object). For more info check this out: http://backbonejs.org/#Collection-Underscore-Methods and scroll down a little to a few of the examples.

Edit:

@Bojangels is right. You also don't want to pass this.collection.model into the template. You just want to pass the collection through (in this case). The collection "contains" the models you care about. Collection.model is an attribute on the collection that says what type of model the collection contains, not a specific instance of the model itself.

As @Tallmaris stated in the comment bellow, the missing piece of the puzzle was to use <%= to putput the values:

  <td><%= user.get('firstname') %></td>
Comments