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="personTemplate" 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>
<div id="content"></div>
CSS
div {
margin-bottom: 20px;
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: {
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;
}
}
}),
PersonView = Backbone.View.extend({
el: "#content",
events: {
"click #btnUpdate": "updateModel"
},
initialize: function() {
// using the initialize to grab the template
// text and cache it on the view object
this.template = _.template($("#personTemplate").text());
// the view subscribes to when the model triggers validation errors
this.model.on("error", this.handleError);
this.model.on("change", function() { alert('model successfully updated.') });
},
render: function() {
// this.$el provides jQuery object for the view's element
this.$el.html(this.template(this.model.toJSON()));
},
// function that manually grabs the DOM input element values
// and then attempts to set the model's properties
updateModel: function() {
var attrs = {
firstName: this.$("#firstName").val(),
lastName: this.$("#lastName").val(),
company: this.$("#company").val(),
position: this.$("#position").val(),
};
this.model.set(attrs);
},
// How the view responds to the model validation error event
...