var UserModel = Backbone.Model.extend({
defaults: {
name: "Pablo",
age: 32
}
});
// Create an instance of the UserModel with our own info
var JorgeModel = new UserModel({
name: "Jorge",
age: 45
});
var UserView = Backbone.View.extend({
// Set the element to which we attach our view
el: "#userList",
// Set up our template
template: _.template($('#userTemplate').html()),
// Initialize our view
initialize: function () {
// Listen for changes to the model and render the view
this.listenTo(this.model, "change", this.render);
// Render the view to start
this.render();
},
// Render the view
render: function () {
// Set the the rendered view to the view’s element
this.$el.html(this.template(this.model.attributes));
// Return this (used for chaining)
return this;
}
});
// Create an instance of the UserView with our JorgeModel
var JorgeView = new UserView({
model: JorgeModel
});
<ul id="userList"></ul>
<script type="text/template" id="userTemplate">
<li class="user">
<p><%= name %> is <%= age %> years old</p>
</li>
</script>
External resources loaded into this fiddle: