Backbone – Models

Models are the heart of any JavaScript MVC application, containing the interactive data as well as a large part of the logic surrounding it: conversions, validations, computed properties, and access control.

Generating a model class:

	var TodoItem = Backbone.Model.extend({});

Generating a model instance:

	var todoItem = new TodoItem({ 
		description: 'Pick up milk', 
		status: 'incomplete' 

To get an attribute:


To set an attribute:

todoItem.set({status: 'complete'});

Fetching Data from the Server

Let’s create a Backbone model to fetch data from the server:

var todoItem = new TodoItem();

URL to get JSON data for model:

todoItem.url = '/todo';

To populate model from server:



{ id: 1, description: 'Pick up milk', status: 'incomplete' }


'Pick up milk'

Now let’s call the RESTful web service:

var TodoItem = Backbone.Model.extend({urlRoot: '/todos'});

Fetch todo with id = 1

var todoItem = new TodoItem({id: 1});

fetch will call GET /todos/1


{ id: 1, description: 'Pick up milk', status: 'incomplete' }

To update the todo:

todoItem.set({description: 'Pick up cookies.'});;

This is calling PUT /todos/1 with JSON params.

Creating & Destroying a New Todo

var todoItem = new TodoItem();
todoItem.set({description: 'Fill prescription.'});; // POST /todos with JSON params

todoItem.get('id');	 // 2


Get JSON from model

To get JSOn from the model:



{ id: 2, description: 'Fill prescription', status: 'incomplete' }

Default Values

Let’s see how we can set default values in Backbone.

	var TodoItem = Backbone.Model.extend({
		defaults: {
			description: 'Empty todo...',
			status: 'incomplete'

	var todoItem = new TodoItem();
	todoItem.get('description'); // 'Empty todo...'
	todoItem.get('status'); //'incomplete'

Models Can Have Events

To listen for an event on a model:

	todoItem.on('event-name', function(){
		alert('event-name happened!');

Run the event:


Special Events

Here are some special events of Backbone:

To listen for changes:

todoItem.on('change', doThing);

<p>Event triggered on change:</p>

var doThing = function() {

Set without triggering event:

	todoItem.set({description: 'Fill prescription.'},
		{silent: true});

Remove event listener'change', doThing);
	todoItem.on(<event>, <method>);

Built-in events:

change When an attribute is modified
change:<attr> When<attr> is modified
destroy When an attribute is modified
sync When a model is destroyed
error When model save or validation fails
all Any triggered event

Be first to comment

Leave a Reply