Created
June 14, 2012 17:01
-
-
Save jcromartie/2931491 to your computer and use it in GitHub Desktop.
Backbone views done right done right?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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