Backbone View Example
A Backbone view connects a model to the DOM, and the clearest way to see that is a working example. This page renders a user card from a model, re-renders it automatically when the model changes, and handles a click event, all in one file using Backbone.js 1.6.0 and an Underscore template.
For the idea behind the code, read what is a view in Backbone.js, then run this to watch a view react to its model.
What you'll learn
What this example builds
The example renders a card showing a user name and a button, and updates the card the moment the underlying model changes.
The behaviour you will see
The view draws itself from a template, so changing the model name and the view re-renders with the new value, with no manual DOM editing. Clicking the button inside the card runs a handler the view declared. This model-to-view binding is what keeps a Backbone interface in sync.
The template and element
A view owns a single DOM element, its el, and usually fills it from an Underscore template.
The template markup
<script type="text/template" id="user-tpl">
<h2><%- name %></h2>
<button class="greet">Greet</button>
</script>
<div id="app"></div>
The <%- %> tag escapes its value, which prevents a cross-site scripting hole when the data comes from users.
The view definition
The view compiles the template once and defines a render method that injects the result into its element.
The view code
var UserView = Backbone.View.extend({
template: _.template($("#user-tpl").html()),
events: {
"click .greet": "onGreet"
},
initialize: function () {
this.listenTo(this.model, "change", this.render);
},
render: function () {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
onGreet: function () {
alert("Hello " + this.model.get("name"));
}
});
Binding the view to a model
The view is created with a model, rendered once, and attached to the page.
Wiring it up
var user = new Backbone.Model({ name: "Ada" });
var view = new UserView({ model: user });
$("#app").html(view.render().el);
user.set("name", "Grace"); // the card updates by itself
Because initialize used listenTo to watch the model change event, the final set triggers render with no extra code. The model side of this is shown in the Backbone model example.
Handling DOM events
Views map DOM events to methods through the events hash, which is cleaner than attaching listeners by hand.
How the events hash works
Each key combines an event type and a CSS selector, such as "click .greet", and the value names the method to run. Backbone delegates these events on the view element, so they keep working even after a re-render replaces the inner markup. That delegation is the main reason to declare events this way rather than calling addEventListener directly.
Common pitfalls
A handful of mistakes cause most view problems.
What usually goes wrong
The most common is using this.model.on instead of this.listenTo, which leaves listeners attached after the view is removed and leaks memory. The second is forgetting to return this from render, which breaks the common view.render().el chain. The third is selecting the whole document with jQuery inside a view rather than scoping queries to this.$el, which causes views to interfere with each other. The concept is covered in what is a view.
Frequently Asked Questions
How does a Backbone view re-render automatically?
Bind the view to its model in initialize using this.listenTo(this.model, 'change', this.render). When the model changes, the change event fires and render runs, so the DOM updates without a manual call.
How do I handle clicks in a Backbone view?
Use the events hash, mapping a key like 'click .greet' to a method name. Backbone delegates the event on the view element, so it keeps working after re-renders replace the inner markup.
What is the el in a Backbone view?
The el is the single DOM element a view owns and renders into. You reach it as this.el, or as a jQuery object via this.$el, and you scope all DOM queries to it.
Why does my Backbone view leak memory?
You are probably using this.model.on instead of this.listenTo. listenTo lets the view stop listening when removed, while on leaves the listener attached after the view is gone.
Read next: the Backbone collection example, or back to the Examples hub.
Want the concept behind the code?
The view explainer covers elements, templates, events, and model binding.
Read: What is a View →