Статьи

Учебник по Backbone — Часть 2. Понимание основ моделей Backbone.js

Когда мы говорим о любом паттерне MV *, модель, несомненно, является наиболее важной частью архитектуры / приложения. Это модель, которая содержит все данные приложения. Наряду с сохранением данных класс модели выполняет различные действия над данными. Действия, такие как возможность проверки данных, возможность сохранения данных и определение доступа к различным частям данных, содержащихся в модели (контроль доступа).

Модели Backbone.js также являются наиболее важными строительными блоками, когда речь идет о создании приложений backbone.js. Он отслеживает данные приложения, выполняет проверку данных и предоставляет механизм для сохранения данных либо локально на локальном хранилище, либо удаленно на сервере с помощью веб-службы.

Ссылка на полную серию:

  1. BackBone Tutorial — Часть 1. Введение в Backbone.Js
  2. Руководство по BackBone — часть 2: Понимание основ моделей Backbone [ ^ ]
  3. Руководство по BackBone — часть 3: подробнее о моделях Backbone [ ^ ]
  4. BackBone Tutorial — Часть 4. Операции CRUD на моделях BackboneJs, использующих службу HTTP REST [ ^ ]
  5. Руководство по BackBone — часть 5: Понимание коллекций Backbone.js [ ^ ]
  6. Руководство по BackBone — часть 6: Понимание представлений Backbone.js [ ^ ]

Создание простой модели backbone.js

Чтобы создать модель магистрали, нам просто нужно расширить класс модели магистрали. Следующий фрагмент кода показывает, как это можно сделать.

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

Кроме того, если мы хотим создать модель, которая наследуется от нашего модельного класса, тогда нам просто нужно расширяться от нашего модельного класса.

var ChildrensBook = Book.extend({
   
});

Создание модели

Базовые модели могут быть просто созданы с использованием нового ключевого слова.

var book = new Book();

Удаление модели

Чтобы удалить модель, нам просто нужно вызвать функцию уничтожения на модели.

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 get successfully deleted.

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 clone of a backbone model we simply need to call the clone method.

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

    var book2 = book.clone();
}

How to specify the model attributes

Backbone models does not enforce defining the attributes in the model definition itself i.e. one can create a model and specify the attributes on the fly. Lets say we want to create 2 attributes in our Book model. lets try to create them on the fly.

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 becomes 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. Lets try to move the attributes in the model definition now.

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.

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 exist in the model or not. To do this we can use the has function on model.

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

Defining Functions in a Model

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

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.

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

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

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

Listening 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. Lets try to hook up the event handler to listen to the model change in our current model.

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

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

        // 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. Lets try to listen to the BookName change only.

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

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

        // 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 for this blog. the idea behind this article was to get familiar with the basic concepts of the backbone model. In next article of this series, we will look at more advanced topics associated with the backbone model. This article has been written from beginner’s perspective, I hope this has been informative.

Download sample code for this article: backboneModelsSampleApp