0

I'm very new to Backbone.js and am trying to get this simple example working. Basically, in jsFiddle when I run the code it tells me that the property "firstname" is not defined.

Here's a link to the fiddle: http://jsfiddle.net/cpeele00/YjUBG/16/

var User = Backbone.Model.extend({});

var UserList = Backbone.Collection.extend({
   model: User
});

var UserView = Backbone.View.extend({
   el: $('#user-list ul'),
   template: _.template($('#user-list-template').html()),
   render: function() {
       this.$el.html(this.template(this.model.toJSON()));
       return this;
   }
});

var user1 = new User();
user1.set({
   firstname: 'Momo',
   lastname: 'Peele'
});

var user2 = new User();
user2.set({
   firstname: 'Bobo',
   lastname: 'Peele'
});


var users = new UserList([user1, user2]);

var userView = new UserView({model: users});

userView.render();

Any help figuring this out would be greatly appreciated.

V/R

Chris

cpeele00
  • 883
  • 4
  • 14
  • 29

1 Answers1

1

Since the model is actually a collection, you need to iterate over it, and apply the template to each model in the collection. One way is to use the Underscore extension Collection.each:

render: function() {
    // clear the view
    this.$el.empty();

    // save a reference to the view object
    var self = this;

    // iterate over the collection
    this.model.each(function(singleModel) {

        // render the model
        self.$el.append(self.template(singleModel.toJSON()));
    });

    return this;
}

Here's the updated Fiddle.

(You could also put the iteration into the template itself if you like, but I think it's generally preferable to keep code in the view, rather than the template.)

McGarnagle
  • 101,349
  • 31
  • 229
  • 260