The Model

Submitted by Erik Wegner on

The Backbone.Model class is a container for data in the first place. Additionally you can write functions that work on the individual records. If you have the birth date as an attribute, you can add a function to calculate the age. When you update an attribute, there may be validation rules.

A Model emits events, when its attributes (i. .e. its data) change. Every Collection and every View can react on these events.

My example changes the title of the link (in the View), if the title (in the Model) changes.

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

The Model only emits the events, if the attributes are updated with the method set.

items.at(2).set("title", "Melone");

The View reacts to the changes in the Model

The current code is saved as attachment file0600.html.