Backbone Template

Standard fiddle

by paulyoder

HTML

<script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
<html>
    <head>
    <script type='text/template' id='contact-row'>
      <td><%= first_name %></td>
      <td><%= last_name %></td>
      <td><%= address %></td>
    </script>

    <script type='text/template' id='contacts-table-header'>
      <thead>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Address</th>
      </thead>
    </script>
  </head>
  <body>
    <button id="add-contact">Add Contact</button>
  </body>
</html>

JavaScript

Contact = Backbone.Model.extend({
  defaults: {
    first_name: "John",
    last_name: "Smith",
    address: "123 Main St"
  }
}); 

Contacts = Backbone.Collection.extend({
  model: Contact
}); 

ContactRow = Backbone.View.extend({
  initialize: function() {
    _.bindAll(this, "render");
    this.template = _.template($("#contact-row").html());
  },

  tagName: 'tr',

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

ContactsView = Backbone.View.extend({        
  initialize: function() {
    _.bindAll(this, "render");
    this.headerTemplate = $("#contacts-table-header").html();
    this.collection.bind("add", this.renderContact, this);
  },

  tagName: 'table',

  render: function() {
    $(this.el).html(this.headerTemplate);

    this.collection.each(function(contact) {
      this.renderContact(contact);
    }, this);

    return this;
  },

  renderContact: function(contact) {
    var contactView = new ContactRow({ model: contact });
    $(this.el).append(contactView.render().el);
  }
});


$(function() {
  //initialize the contacts collection and add some
  contacts = new Contacts();
  contacts.add(new Contact());
  contacts.add(new Contact());

  //only need to render the ContactsView once
  var view = new ContactsView({ collection: contacts });
  $("body").append(view.render().el);

  //adding a contact to the contacts list when the
  //button is clicked
  $("#add-contact").click(function() {
    contacts.add(new Contact());
  });
});