Add new comment

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.

About text formats

Activitypub

  • Allowed HTML tags: <a href hreflang> <em> <strong> <ul type> <ol start type='1 A I'> <li> <dl> <dt> <dd> <h2 id='jump-*'> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.