Tuesday, April 17, 2012

backbone collection view example

//MODEL
var Appointment = Backbone.Model.extend({});

var AppointmentList = Backbone.Collection.extend({
  model: Appointment
});

//VIEWS
var AppointmentView = Backbone.View.extend({
  template: _.template('">' +
                        '<%= title %>' +
                        'x'),
  

  render: function(){
    this.$el.html(this.template(this.model.toJSON()));
    return this;
  }
});

//APPLICATION.JS
var AppointmentListView = Backbone.View.extend({
  render: function(){
    this.collection.forEach(this.addOne, this);
  },
  addOne: function(model){
    var appointmentView = new AppointmentView({model: model})
    appointmentView.render()
    this.$el.append(appointmentView.el)
  }
});

2 comments:

  1. Author, I think this example requires revision. It does not serve as a "backbone collection view example" as the blog title states.

    Notice that "AppointmentListView" (line 22) references "this.collection" (line 24), but collection is not available to the view.

    The collection "AppointmentList" is never instantiated in this example, it is only defined. "collection" is neither scoped in nor passed to AppointmentListView, thus making it inaccessible.

    ReplyDelete