Backbone.js Introduction to Views
by ifandelse
HTML
<script src="http://documentcloud.github.com/underscore/underscore.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone.js"></script>
<script id="editTemplate" type="text/html">
<fieldset>
<div class="row">
<label for="firstName">First Name:</label>
<input type="text" id="firstName" value="<%= firstName %>">
</div>
<div class="row">
<label for="lastName">Last Name:</label>
<input type="text" id="lastName" value="<%= lastName %>">
</div>
<div class="row">
<label for="company">Company:</label>
<input type="text" id="company" value="<%= company %>">
</div>
<div class="row">
<label for="position">Position:</label>
<input type="text" id="position" value="<%= position %>">
</div>
<div class="row">
<input type="button" value="Update Model" id="btnUpdate">
</div>
</fieldset>
</script>
<script id="listTemplate" type="text/html">
<ul>
<% _.each(people, function( person ) { %>
<li data-val="<%= person.id %>"><%= person.lastName %>, <%= person.firstName %></li>
<% }) %>
</ul>
</script>
<div id="content"></div>
CSS
div {
margin-bottom: 5px;
padding: 5px;
}
label {
float: left;
width: 100px;
}
.row {
clear:both;
}
.row input[type="text"] {
width: 250px;
}
JavaScript
var PersonModel = Backbone.Model.extend({
// default values for the model
defaults: {
id: null,
firstName: "",
lastName: "",
company: "",
position: ""
},
// a simple validation function
validate: function(attrs) {
var errors = [];
if (!attrs.firstName) {
errors.push("I kinda need to know what to call you. First Name maybe?");
}
if (!attrs.lastName) {
errors.push("What - they don't have last names where you come from?");
}
if (errors.length) {
return errors;
}
}
}),
PeopleCollection = Backbone.Collection.extend({
model: PersonModel
}),
PeopleView = Backbone.View.extend({
el: "#content",
events: {
"click li": "handleEdit"
},
initialize: function() {
// using the initialize to grab the template
// text and cache it on the view object
this.template = _.template($("#peopleTemplate").text());
// the view subscribes to when the model triggers validation errors
this.collection.on("error", this.handleError);
this.collection.on("change", function() { alert('model successfully updated.') });
},
render: function() {
// this.$el provides jQuery object for the view's element
this.$el.html(this.template({ people: this.collection.toJSON() }));
},
handleEdit: function( e ) {
var elem = $(e.currentTarget);
}
}),
people;
people = new PeopleView({
collection: new PeopleCollection([
{
id: 0,
firstName: "Ralph",
lastName: "Whitbeck",
company: "appendTo",
position: "Resident Genius and Smart Aleck"
},
{
id: 1,
...