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:
jQuery('body').append(masterview.$el);
The browser inspector window shows, that the element exists:
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 (options.data) { this.data = options.data; } }, render: function() { this.$el.html(this.template(this.data)); 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 }); masterview.$el.append(itemview.render().el); });
The hyperlinks are already visible on the screen, the corresponding DOM elements are shown in the inspector:
The current code is saved as attachment file0300.html.