Cover by Alex MacCaw

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

Views

Backbone views are not templates themselves, but are control classes that handle a model’s presentation. This can be confusing, because many MVC implementations refer to views as chunks of HTML or templates that deal with events and rendering in controllers. Regardless, in Backbone, it is a view “because it represents a logical chunk of UI, responsible for the contents of a single DOM.”

Like models and collections, views are created by extending one of Backbone’s existing classes—in this case, Backbone.View:

var UserView = Backbone.View.extend({
  initialize: function(){ /* ... */ },
  render: function(){ /* ... */ }
});

Every view instance has the idea of a current DOM element, or this.el, regardless of whether the view has been inserted into the page. el is created using the attributes from the view’s tagName, className, or id properties. If none of these is specified, el is an empty div:

var UserView = Backbone.View.extend({
  tagName: "span",
  className: "users"
});

assertEqual( (new UserView).el.className, "users" );

If you want to bind the view onto an existing element in the page, simply set el directly. Clearly, you need to make sure this view is set up after the page has loaded; otherwise, the element won’t yet exist:

var UserView = Backbone.View.extend({
  el: $(".users")     
});

You can also pass el as an option when instantiating a view, as with the tagName, className, and id properties:

new UserView({id: "followers"});

Rendering Views

Every view also has a render() function, which by ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required