scapegoat17 scapegoat17 - 1 year ago 118
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:

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

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() {
var template = _.template($('#user-list-template').html(), {users: this.collection.model});

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


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 Source

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: and scroll down a little to a few of the examples.


@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>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download