Add new comment

The concept of a View

Submitted by Erik Wegner on Tue, 02/25/2014 - 21:23

To oversimplify the View class, it can be used to bring data to the screen. This example should create a simple list. Let's start by creating some items:

var d = [];
d.push( { id: 17, title: 'Apfel'} );
d.push( { id: 23, title: 'Birne'} );
d.push( { id: 42, title: 'Orange'} );

It is easy and useful to have View for the list itself (contained in the variable d) and for each item in the list.

The View for the Array is defined here:

var MasterView = Backbone.View.extend({
	tagName: "ul",
	className: "masterview"

var masterview = new MasterView();

The object masterview is already instantiated. Its property masterview.$el is a reference to its jQuery object, which exists only in memory at the moment and is not included in the DOM tree of the browser. This can be done by this command:


The browser inspector window shows, that the element exists:

The view is visible in the DOM tree.

The current code is saved as attachment file0200.html.

The View for each list entry is defined in a similar manner:

var ItemView = Backbone.View.extend({
	tagName: "li",
	className: "backboneitem",
	template: _.template('<a href' + '="show?' + 'ID=<%= id %>"><%= title %></a>'),

	initialize: function(options) {
	    if ( { =;
	render: function() {
		return this;

To instantiate the objects, I use a loop from the Underscore.js library.

_.each(d, function(element, index, list) { 
	var itemview = new ItemView({ data: element });

The hyperlinks are already visible on the screen, the corresponding DOM elements are shown in the inspector:

The list of hyperlinks

The current code is saved as attachment file0300.html.