//

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:

todoItem.get('description');

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:

todoItem.fetch();

Result:

{ id: 1, description: 'Pick up milk', status: 'incomplete' }
todoItem.get('description');

Result:

'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});
todoItem.fetch();

fetch will call GET /todos/1

Result:

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

To update the todo:

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

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

Creating & Destroying a New Todo

var todoItem = new TodoItem();
todoItem.set({description: 'Fill prescription.'});

todoItem.save(); // POST /todos with JSON params

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

todoItem.destroy();

Get JSON from model

To get JSOn from the model:

todoItem.toJSON();

Result:

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

Default Values

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

js
    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:

todoItem.trigger('event-name');

Special Events

Here are some special events of Backbone:

To listen for changes:

todoItem.on('change', doThing);

Event triggered on change:
```js
var doThing = function() {
    ...
}

Set without triggering event:

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

Remove event listener

todoItem.off('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