Add new comment

The Collection

Submitted by Erik Wegner on

The class Backbone.Collection is used to organize the elements in a list.

At this point, the _.each loop will no longer be necessary. The inner code is added to the view as the addOne function:

var MasterView = Backbone.View.extend({
	tagName: "ul",
	className: "masterview",
	addOne: function(element) {
		var itemview = new ItemView({ data: element });
		this.$el.append(itemview.render().el);
	}
});

var masterview = new MasterView();
jQuery('body').append(masterview.$el);

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.toJSON));
		return this;
	}
});

The function render in the ItemView class has been adopted to the fact that the function argument is already a Backbone.Model.

The next lines of code define a collection and make sure that the inner elements automatically appear in the shown list.

var Items = Backbone.Collection.extend();
var items = new Items();

masterview.listenTo(items, "add", masterview.addOne);

If you now add elements to the collection (either in the browser's console or in other code), they show up on screen..

items.add({ id: 17, title: 'Apfel' });
items.add({ id: 23, title: 'Birne' });
items.add({ id: 42, title: 'Orange' });

The current code is saved as attachment file0400.html.

Please note: The instructions can be executed many times, the collection checks the value of the field id and does not add elements with an already existing id.

Adding items already results in an update to the list display. But nothing happens when you remove an element from the collection. This event can be processed in the ItemView. Its initialize function is a good place for that:

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;
			this.listenTo(this.data, "remove", this.remove);
		}
	},
	
	render: function() {
		this.$el.html(this.template(this.data.toJSON()));
		return this;
	}
});

If the entire code block is executed, you can use the browser console to modify the items in the collection. The displayed list is updated immediately:

var birne = items.at(1);
items.remove(birne);
var kirsche = { id: 19, title: "Kirsche" };
items.add(kirsche);

Die Manipulation der Collection

The current code is saved as attachment file0500.html.

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.