Click here to Skip to main content
15,513,489 members
Articles / Web Development / HTML
Article
Posted 12 Jul 2014

Stats

73.9K views
1.3K downloads
14 bookmarked

BackBone Tutorial – Part 2: Understanding the Basics of Backbone Models

Rate me:
Please Sign up or sign in to vote.
4.97/5 (26 votes)
23 Feb 2015CPOL4 min read
In this article, we will discuss the basics of backbone models.

Introduction

In this article, we will discuss the basics of backbone models.

Background

When we talk about any MV* pattern, model is undoubtedly the most important part of the architecture/application. It's the model that contains all the application data. Along with keeping the data, the model class performs various set of actions on the data. Actions like possibility to validate the data, possibility to persist the data, defining access to various parts of data contained in the model (access control).

Backbone.js models are also the most important building blocks when it comes to building backbone.js applications. It keeps track of application data, performs validations on data and provides a mechanism to persist the data either locally on localstorage or remotely on a server using a web service.

Link to complete series:

  1. BackBone Tutorial – Part 1: Introduction to Backbone.Js[^]
  2. BackBone Tutorial – Part 2: Understanding the basics of Backbone Models[^]
  3. BackBone Tutorial – Part 3: More about Backbone Models[^]
  4. BackBone Tutorial – Part 4: CRUD Operations on BackboneJs Models using HTTP REST Service[^]
  5. BackBone Tutorial – Part 5: Understanding Backbone.js Collections[^]
  6. BackBone Tutorial – Part 6: Understanding Backbone.js Views[^]
  7. BackBone Tutorial – Part 7: Understanding Backbone.js Routes and History[^]
  8. BackBone Tutorial – Part 8: Understanding Backbone.js Events[^]

Creating a Simple backbone.js Model

To create a backbone model, we simply need to extend the backbone model class. The following code snippet shows how this can be done.

JavaScript
var Book = Backbone.Model.extend({
   
});

Furthermore, if we want to create a model that inherits from our model class, then we just need to extend from our model class.

JavaScript
var ChildrensBook = Book.extend({
   
});

Instantiating a Model

Backbone models can simply be instantiated by using the new keyword.

JavaScript
var book = new Book();

Deleting a Model

To delete a model, we just need to call the destroy function on the model.

JavaScript
book.destroy();

Sometimes, deleting a model could take some time (depending on the size of the model). In such cases, we can define a function that will be called when the model gets successfully deleted.

JavaScript
book.destroy({
    success: function () {
        alert("The model has been destroyed successfully");
    }
});

Cloning a Model

Often times, we would want to have a deep copied object or clone of a model. To create a clone of a backbone model, we simply need to call the clone method.

JavaScript
function cloneModel() {
    var book = new Book();

    var book2 = book.clone();
}

How to Specify the Model Attributes

Backbone models do not enforce defining the attributes in the model definition itself, i.e., one can create a model and specify the attributes on the fly. Let's say we want to create 2 attributes in our Book model. Let's try to create them on the fly.

JavaScript
var book = new Book({
    ID: 1,
    BookName: "Sample book"
});

Default Values of Model Attributes

Now creating the attributes on the fly is supported by the backbone models and it is a very powerful feature. But this feature actually proves to be a maintenance nightmare when it comes to working with large scale application. From a maintainable application perspective and also from a best practices perspective, I would like the possibility to define my models attributes in my model definition itself.

To accomplish this, the default function can be used. The default function is used to specify the default attributes of the model and their default values. Let's try to move the attributes in the model definition now.

JavaScript
var Book = Backbone.Model.extend({
    defaults: {
        ID: "",
        BookName: ""
    },    
});

This way, just instantiating the model will be enough and the created models will have these attributes associated with them.

Setting and Getting Model Attributes

Once we specify the model attributes, we need to be able to get and set their values too. To do this, we can use the get and set functions on the model.

JavaScript
var book = new Book();

book.set("ID", 3);
book.set("BookName", "C# in a nutshell");

var bookId = book.get('ID');
var bookName = book.get('BookName');

How to Check Attribute Existence

Since backbone allows us to add attributes on the fly, we need some way to identify whether a particular attribute exists in the model or not. To do this, we can use the has function on model.

JavaScript
book.has('ID');      // true
book.has('author');  // false

Defining Functions in a Model

We can also define our functions in the model classes. Let's try to create a simple function in our model class.

JavaScript
var Book = Backbone.Model.extend({
    defaults: {
        ID: "",
        BookName: ""
    },

    showAlert: function () {
        alert('ID: ' + this.get('ID') + ', BookName: ' + this.get('BookName'));
    }
});

The initialize Function

Whenever we create a model, the backbone will call its initialize function. We can override this function to provide custom behavior to it.

JavaScript
var Book = Backbone.Model.extend({
    defaults: {
        ID: "",
        BookName: ""
    },

    initialize: function(){
        console.log('Book has been initialized');
    },

    showAlert: function () {
        alert('ID: ' + this.get('ID') + ', BookName: ' + this.get('BookName'));
    }
});

Listening to Model Attribute Changes

We can also use the events to listen to the model changes. This can be done by listening to the change event. Backbone raises a change event whenever any model attribute is changed. For each attribute, we can use hasChanged method to check if that attribute has been changed or not. Let's try to hook up the event handler to listen to the model change in our current model.

JavaScript
var Book = Backbone.Model.extend({
    defaults: {
        ID: "",
        BookName: ""
    },

    initialize: function(){
        console.log('Book has been initialized');

        // Lets hook up some event handers to listen to model change
        this.on('change',  function() {
            if(this.hasChanged('ID')){
                console.log('ID has been changed');
            }
            if(this.hasChanged('BookName')){
                console.log('BookName has been changed');
            }
        });
    },

    showAlert: function () {
        alert('ID: ' + this.get('ID') + ', BookName: ' + this.get('BookName'));
    }
});

If we have a lot of attributes and we are interested in listening to change for any specific attribute, then perhaps we can specify that too in the change event binding. Let's try to listen to the BookName change only.

JavaScript
var Book = Backbone.Model.extend({
    defaults: {
        ID: "",
        BookName: ""
    },

    initialize: function () {
        console.log('Book has been initialized');

        // Lets hook up some event handers to listen to model change
        this.on('change:BookName', function () {
            console.log('Message from specific listener: BookName has been changed');
        });
    },

    showAlert: function () {
        alert('ID: ' + this.get('ID') + ', BookName: ' + this.get('BookName'));
    }
});

Point of Interest

So that is it for this blog. The idea behind this article was to get familiar with the basic concepts of the backbone model. In the next article of this series, we will look at more advanced topics associated with the backbone model. This article has been written from a beginner’s perspective, I hope this has been informative.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India

I Started my Programming career with C++. Later got a chance to develop Windows Form applications using C#. Currently using C#, ASP.NET & ASP.NET MVC to create Information Systems, e-commerce/e-governance Portals and Data driven websites.

My interests involves Programming, Website development and Learning/Teaching subjects related to Computer Science/Information Systems. IMO, C# is the best programming language and I love working with C# and other Microsoft Technologies.

  • Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4

If you like my articles, please visit my website for more: www.rahulrajatsingh.com[^]

  • Microsoft MVP 2015

Comments and Discussions

 
GeneralThanks! Pin
Alireza_136215-Apr-16 10:21
Alireza_136215-Apr-16 10:21 
GeneralVery Good Pin
Member 1082408414-Sep-15 19:14
Member 1082408414-Sep-15 19:14 
QuestionNice article Rahul! Pin
Member 1191183016-Aug-15 4:44
Member 1191183016-Aug-15 4:44 
QuestionNice article to start up Pin
Avadhesh Kumar Maurya23-Feb-15 23:55
Avadhesh Kumar Maurya23-Feb-15 23:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.