Backbone.js – Introduction to Models

In my last post, I introduced Backbone.js in a casual, non-formal way, as an ice-breaker. Now that you know how useful and indispensable Backbone is for a library of its size, we will get into some technicalities and talk like the geeks we are :)

Backbone.js comes with the building blocks – Models, Views, Collections, Routers, Events, etc. that can be reused/extended as per the use case to create a manageable, maintainable and robust JavaScript application.

We will begin with ‘the Model

The Model –

Backbone Model can be thought of as a Java class which encapsulates the data and provides the accessor and mutator functions to manipulate it. This type of interaction provided by Model is essential for implementing a popular javaScript design pattern called Observer design pattern – the model changes, other listeners (views, collections, etc) update themselves accordingly.

The following code illustrates a simple usage of Backbone Model –

1
2
3
4
5
6
7
8
9
10
//create Backbone Model
var Car=new Backbone.Model({name: 'Audi', model: 'R8', orderDate:'5/7/2013' });
//accessor method
Car.get('name');  //returns 'Audi'
//Assign observer
Car.on('change',function(){
    console.log('Some details of Car changed');
});
//Change the data using setter
Car.set('name', 'Jaguar');  //triggers the logging 'Some details of Car changed'

Above snippet demonstrates a basic scenario in which a simple Car Model is created and processed as explained in the comments. The real world implementation and usage of an actual Backbone Model is far more advanced. This is where you need to extend Backbone’s Model with your application specific logic.

Following example illustrates my point –

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//extend Backbone's Model with your own custom model by creating new constructor
var Car = Backbone.Model.extend({
    waitingPeriod : function(){
        return (new Date() - this.get('orderDate') );
    }
});
//create object of the above defined Car Model
var car=new Car({
    name :  'Audi',
    make : 'R8',
    orderDate : '5/7/2013'
});
//using the tailor-made functions
car.waitingPeriod();
Pretty neat right?

So, that’s about all that Models can do – tie up your data and provide an object-oriented way to access and manipulate it, provide for Observer Pattern implementation, persistence, etc.

We can also connect the data in models to server using sync() and other useful methods that will be covered in detail as a separate topic. The most important feature of Backbone Model is the ease and simplicity with which it can be used especially if your server-side APIs are restful/ JSON API.

Read more about the Backbone Model at this official document.

In the next post of the series, I will talk about the most exciting part of Backbone – the Backbone View. Stay tuned :)

Vidhi Zala

Leave a Reply