Home Reference Source Repository
import View from 'backbone-es6/src/View.js'
public class | source

View

Extends:

Events → View

Backbone.View - Represents a logical chunk of UI in the DOM. (http://backbonejs.org/#View)

Backbone Views are almost more convention than they are actual code. A View is simply a JavaScript object that represents a logical chunk of UI in the DOM. This might be a single item, an entire list, a sidebar or panel, or even the surrounding frame which wraps your whole app. Defining a chunk of UI as a View allows you to define your DOM events declaratively, without having to worry about render order ... and makes it easy for the view to react to specific changes in the state of your models.

Creating a Backbone.View creates its initial element outside of the DOM, if an existing element is not provided...

Example if working with Backbone as ES6 source:

Example:


import Backbone from 'backbone';

export default class MyView extends Backbone.View
{
   constructor(options)
   {
      super(options);
      ...
   }

   initialize()
   {
      ...
   }
   ...
}

To use a custom $el / element define it by a getter method:

   get el() { return 'my-element'; }

Likewise with events define it by a getter method:

   get events()
   {
      return {
        'submit form.login-form': 'logIn',
        'click .sign-up': 'signUp',
        'click .forgot-password': 'forgotPassword'
      }
   }

Constructor Summary

Public Constructor
public

constructor(options: object)

There are several special options that, if passed, will be attached directly to the view: model, collection, el, id, className, tagName, attributes and events.

Member Summary

Public Members
public

Cached jQuery context for element.

public

Client ID

public

Cached element

public get

The default tagName of a View's element is "div".

Method Summary

Public Methods
public

$(selector: string): Element | $

If jQuery is included on the page, each view has a $ function that runs queries scoped within the view's element. If you use this scoped jQuery function, you don't have to use model ids as part of your query to pull out specific elements in a list, and can rely much more on HTML class attributes.

public

delegate(eventName: string, selector: string, listener: function): View

Add a single event listener to the view's element (or a child element using selector). This only works for delegate-able events: not focus, blur, and not change, submit, and reset in Internet Explorer.

public

Uses jQuery's on function to provide declarative callbacks for DOM events within a view. If an events hash is not passed directly, uses this.events as the source. Events are written in the format {"event selector": "callback"}. The callback may be either the name of a method on the view, or a direct function body. Omitting the selector causes the event to be bound to the view's root element (this.el).

public abstract

Initialize is an empty function by default.

public

Removes a view and its el from the DOM, and calls stopListening to remove any bound events that the view has listenTo'd.

public abstract

The default implementation of render is a no-op.

public

setElement(element: string | object): View

If you'd like to apply a Backbone view to a different DOM element, use setElement, which will also create the cached $el reference and move the view's delegated events from the old element to the new one.

public

undelegate(eventName: string, selector: string, listener: function): View

A finer-grained undelegateEvents for removing a single delegated event.

public

Removes all of the view's delegated events. Useful if you want to disable or remove a view from the DOM temporarily.

Protected Methods
protected

Produces a DOM element to be assigned to your view.

protected

Ensure that the View has a DOM element to render into.

protected

Remove this view's element from the document and all event listeners attached to it. Exposed for subclasses using an alternative DOM manipulation API.

protected

_setAttributes(attributes: object)

Set attributes from a hash on this view's element. Exposed for subclasses using an alternative DOM manipulation API.

protected

Creates the this.el and this.$el references for this view using the given el.

Inherited Summary

From class Events
public

bind(): *

Delegates to on.

public

listenTo(obj: object, name: string, callback: function): Events

Tell an object to listen to a particular event on an other object.

public

listenToOnce(obj: object, name: string, callback: function): Events

Just like listenTo, but causes the bound callback to fire only once before being removed.

public

off(name: string, callback: function, context: object): Events

Remove a previously-bound callback function from an object.

public

on(name: string, callback: function, context: object): *

Bind a callback function to an object.

public

once(name: string, callback: function, context: object): *

Just like on, but causes the bound callback to fire only once before being removed.

public

stopListening(obj: object, name: string, callback: function): Events

Tell an object to stop listening to events.

public

Trigger callbacks for the given event, or space-delimited list of events.

public

unbind(): *

Delegates to off.

Public Constructors

public constructor(options: object) source

There are several special options that, if passed, will be attached directly to the view: model, collection, el, id, className, tagName, attributes and events. If the view defines an initialize function, it will be called when the view is first created. If you'd like to create a view that references an element already in the DOM, pass in the element as an option: new View({el: existingElement})

Override:

Events#constructor

Params:

NameTypeAttributeDescription
options object

Default options which are mixed into this class as properties via _.pick against s_VIEW_OPTIONS. Options also is passed onto the initialize() function.

See:

Public Members

public $el: object source

Cached jQuery context for element.

public cid: number source

Client ID

public el: Element source

Cached element

public get tagName: string: string source

The default tagName of a View's element is "div".

Return:

string

Public Methods

public $(selector: string): Element | $ source

If jQuery is included on the page, each view has a $ function that runs queries scoped within the view's element. If you use this scoped jQuery function, you don't have to use model ids as part of your query to pull out specific elements in a list, and can rely much more on HTML class attributes. It's equivalent to running: view.$el.find(selector)

Params:

NameTypeAttributeDescription
selector string

A string containing a selector expression to match elements against.

Return:

Element | $

Example:

class Chapter extends Backbone.View {
   serialize() {
      return {
         title: this.$(".title").text(),
         start: this.$(".start-page").text(),
         end:   this.$(".end-page").text()
      };
   }
}

See:

public delegate(eventName: string, selector: string, listener: function): View source

Add a single event listener to the view's element (or a child element using selector). This only works for delegate-able events: not focus, blur, and not change, submit, and reset in Internet Explorer.

Params:

NameTypeAttributeDescription
eventName string

One or more space-separated event types and optional namespaces.

selector string

A selector string to filter the descendants of the selected elements that trigger the event.

listener function

A function to execute when the event is triggered.

Return:

View

See:

public delegateEvents(events: object): View source

Uses jQuery's on function to provide declarative callbacks for DOM events within a view. If an events hash is not passed directly, uses this.events as the source. Events are written in the format {"event selector": "callback"}. The callback may be either the name of a method on the view, or a direct function body. Omitting the selector causes the event to be bound to the view's root element (this.el). By default, delegateEvents is called within the View's constructor for you, so if you have a simple events hash, all of your DOM events will always already be connected, and you will never have to call this function yourself.

The events property may also be defined as a function that returns an events hash, to make it easier to programmatically define your events, as well as inherit them from parent views.

Using delegateEvents provides a number of advantages over manually using jQuery to bind events to child elements during render. All attached callbacks are bound to the view before being handed off to jQuery, so when the callbacks are invoked, this continues to refer to the view object. When delegateEvents is run again, perhaps with a different events hash, all callbacks are removed and delegated afresh — useful for views which need to behave differently when in different modes.

A single-event version of delegateEvents is available as delegate. In fact, delegateEvents is simply a multi-event wrapper around delegate. A counterpart to undelegateEvents is available as undelegate.

Callbacks will be bound to the view, with this set properly. Uses event delegation for efficiency. Omitting the selector binds the event to this.el.

Params:

NameTypeAttributeDescription
events object

hash of event descriptions to bind.

Return:

View

Example:

Older `extend` example:
var DocumentView = Backbone.View.extend({
   events: {
      "dblclick"                : "open",
      "click .icon.doc"         : "select",
      "contextmenu .icon.doc"   : "showMenu",
      "click .show_notes"       : "toggleNotes",
      "click .title .lock"      : "editAccessLevel",
      "mouseover .title .date"  : "showTooltip"
   },

   render: function() {
      this.$el.html(this.template(this.model.attributes));
      return this;
   },

   open: function() {
      window.open(this.model.get("viewer_url"));
   },

   select: function() {
      this.model.set({selected: true});
   },

  ...
});
Converting the above `extend` example to ES6:
class DocumentView extends Backbone.View {
   get events() {
      return {
         "dblclick"                : "open",
         "click .icon.doc"         : "select",
         "contextmenu .icon.doc"   : "showMenu",
         "click .show_notes"       : "toggleNotes",
         "click .title .lock"      : "editAccessLevel",
         "mouseover .title .date"  : "showTooltip"
      };
   }

   render() {
      this.$el.html(this.template(this.model.attributes));
      return this;
   }

   open() {
      window.open(this.model.get("viewer_url"));
   }

   select() {
      this.model.set({selected: true});
   }
   ...
}

See:

public abstract initialize() source

Initialize is an empty function by default. Override it with your own initialization logic.

See:

public remove(): View source

Removes a view and its el from the DOM, and calls stopListening to remove any bound events that the view has listenTo'd.

Return:

View

See:

public abstract render(): View source

The default implementation of render is a no-op. Override this function with your code that renders the view template from model data, and updates this.el with the new HTML. A good convention is to return this at the end of render to enable chained calls.

Backbone is agnostic with respect to your preferred method of HTML templating. Your render function could even munge together an HTML string, or use document.createElement to generate a DOM tree. However, we suggest choosing a nice JavaScript templating library. Mustache.js, Haml-js, and Eco are all fine alternatives. Because Underscore.js is already on the page, _.template is available, and is an excellent choice if you prefer simple interpolated-JavaScript style templates.

Whatever templating strategy you end up with, it's nice if you never have to put strings of HTML in your JavaScript. At DocumentCloud, we use Jammit in order to package up JavaScript templates stored in /app/views as part of our main core.js asset package.

Return:

View

Example:

class Bookmark extends Backbone.View {
   get template() { return _.template(...); }

   render() {
      this.$el.html(this.template(this.model.attributes));
      return this;
   }
}

See:

public setElement(element: string | object): View source

If you'd like to apply a Backbone view to a different DOM element, use setElement, which will also create the cached $el reference and move the view's delegated events from the old element to the new one.

Params:

NameTypeAttributeDescription
element string | object

A CSS selector or an HTML string, a jQuery context or an element.

Return:

View

See:

public undelegate(eventName: string, selector: string, listener: function): View source

A finer-grained undelegateEvents for removing a single delegated event. selector and listener are both optional.

Params:

NameTypeAttributeDescription
eventName string

One or more space-separated event types and optional namespaces.

selector string

A selector which should match the one originally passed to .delegate().

listener function

A handler function previously attached for the event(s).

Return:

View

See:

public undelegateEvents(): View source

Removes all of the view's delegated events. Useful if you want to disable or remove a view from the DOM temporarily.

Return:

View

See:

Protected Methods

protected _createElement(tagName: string): Element source

Produces a DOM element to be assigned to your view. Exposed for subclasses using an alternative DOM manipulation API.

Params:

NameTypeAttributeDescription
tagName string

Name of the tag element to create.

Return:

Element

See:

protected _ensureElement() source

Ensure that the View has a DOM element to render into. If this.el is a string, pass it through $(), take the first matching element, and re-assign it to el. Otherwise, create an element from the id, className and tagName properties.

protected _removeElement() source

Remove this view's element from the document and all event listeners attached to it. Exposed for subclasses using an alternative DOM manipulation API.

See:

protected _setAttributes(attributes: object) source

Set attributes from a hash on this view's element. Exposed for subclasses using an alternative DOM manipulation API.

Params:

NameTypeAttributeDescription
attributes object

An object defining attributes to associate with this.$el.

protected _setElement(el: string | object) source

Creates the this.el and this.$el references for this view using the given el. el can be a CSS selector or an HTML string, a jQuery context or an element. Subclasses can override this to utilize an alternative DOM manipulation API and are only required to set the this.el property.

Params:

NameTypeAttributeDescription
el string | object

A CSS selector or an HTML string, a jQuery context or an element.