Skip to content

Instantly share code, notes, and snippets.

@jcromartie
Created June 14, 2012 17:01
Show Gist options
  • Save jcromartie/2931491 to your computer and use it in GitHub Desktop.
Save jcromartie/2931491 to your computer and use it in GitHub Desktop.
Backbone views done right done right?
var TableViewRow = Backbone.View.extend({
tagName: "tr",
template: _.template("<td><%= firstName %></td><td><%= lastName %></td>"),
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
var TableView = Backbone.View.extend({
tagName: "table",
template: _.template("<thead><th>First Name</th><th>Last Name</th></thead><tbody></tbody>"),
initialize: function(opts) {
_.bindAll(this, "addPerson");
},
addPerson: function(person) {
var personView = new TableViewRow({model: person});
this.listContainer.append(personView.render().el);
},
render: function() {
this.$el.html(this.template());
this.listContainer = this.$el.find("> tbody");
this.collection.each(this.addPerson);
return this;
}
});
var me = new Backbone.Model({firstName: "John", lastName: "Cromartie"});
var you = new Backbone.Model({firstName: "Mystery", lastName: "Coder"});
var myTable = new TableView({collection: new Backbone.Collection([me, you])});
$("body").append(myTable.render().el);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment