Archive for May, 2014

The Backbone.js models are javascript objects which stores data for the application.In this post we will see how we can create and initialize these models by extending the Backbone.Model object. Let’s start with a very simple example as shown in the snippet below:

image

Here we have used the extend function of Backbone.Model to create the model definition and instantiate it. This is a simple object without any properties. We can create it with properties as shown below:

image

We will see the following in browser console.

Object t: {"a":1,"b":2}

Backbone.js also provides an option to set the default values for model properties by setting the default property in extend as shown below:

image

Here, while defining the model we are setting defaults values of “a” and “b” as 1 and 2. While creating the object we are overriding the default value of “a” with 3. We will see the following browser console.

Object t: {"a":3,"b":2}

Backbone.js also provides an option to write an initializer by exposing the initialize property in the extend.

image

Here we can see in the console,

Object is initialized.{"a":3,"b":2}

If we want further customization then we can override the constructor itself as shown below:

image

Here, we can see the following output in the console.

Object is created

Object t: undefined

Here we have used our constructor but the we can see that the object is not properly initialized.This is because we have not invoked the constructor for Backbone.Model from our own constructor.

image

In the above code, we have invoked the Backbone.Model constructor by using the apply function on it and the object is properly initialized as evident from console log.

Custom constructor called..
Object is initialized.{"a":3,"b":2}
Object t: {"a":3,"b":2}

So its evident that initialize, defaults etc. are all are invoked from constructor of Backbone.Model. The constructor property completely overrides the Backbone.Model default constructor, so unless we need some very special object creation logic it is advisable not to use this.

Advertisements