+1

Learn about Model in Backbone.js

Introduction: When we talk about any MVC model, Model is undoubtedly the most important part of the architecture of applications. Model is where all application data is stored. Along with keeping the data, the Model class performs various actions on the data. Actions such as the ability to validate data, the ability to maintain data, define access to different parts of the data contained in the model. Models in Backbone.js are also the most important component when building the backbone.js application. It monitors application data, performs validation on data, and provides a mechanism to maintain local data on localstorage.

Initialize function and Constructor in Model initialization: Whenever we create a model, BackboneJS will invoke its constructor. We can override this function to provide custom behavior for it.

var Book = Backbone.Model.extend({
    defaults: {
        ID: "",
        BookName: ""
    },
    initialize: function () {
        console.log('Book has been intialized');       
    },
});

Generate a contructor in our model, we can declare a model as follows:

var Book = Backbone.Model.extend({
    defaults: {
        ID: "",
        BookName: ""
    },
    initialize: function () {
        console.log('Book has been intialized');       
    },
    constructor: function (attributes, options) {
        console.log('Book\'s constructor had been called');
        Backbone.Model.apply(this, arguments);
    },
});

Model identifiers - id, cid and idAttribute: Each model when initialized needs to be uniquely identified. BackboneJs provides us with the Model IDs. First look at is cid. The cid or client ID is automatically generated by BackboneJS so that each model can be uniquely identified on the client.

var book1 = new Book();
var book2 = new Book();

Backbone also provides an identifier id to uniquely identify a Model. This is the id that will be used to determine the model when the model data is actually synchronized to the server. The cid is more useful for debugging purposes but the id attribute will determine the uniqueness of the model when joining the CRUD operation.

var Book = Backbone.Model.extend({
    defaults: {
        ID: "",
        BookName: ""
    },
    idAttribute: "ID",
    initialize: function () {
        console.log('Book has been intialized');
    },
    constructor: function (attributes, options) {
        console.log('Book\'s constructor had been called');
        Backbone.Model.apply(this, arguments);
    },
});

Validating in Models: When working on multiple business applications, I would normally be asked to validate models before show data. Backbone provides a very easy way to perform validating, which is generally just enforcing the function validate:

var Book = Backbone.Model.extend({
    defaults: {
        ID: "",
        BookName: ""
    },
    idAttribute: "ID",
    initialize: function () {
        console.log('Book has been intialized');
        this.on("invalid", function (model, error) {
            console.log("Houston, we have a problem: " + error)
        });
    },
    constructor: function (attributes, options) {
        console.log('Book\'s constructor had been called');
        Backbone.Model.apply(this, arguments);
    },
    validate: function (attr) {
        if (attr.ID <= 0) {
            return "Invalid value for ID supplied."
        }
    }
});

The backbone model supports storing data to the server through the use of restful api. To save model information, we need to declare the urlRoot in the backbone model and call the save () function. The method will trigger validations and if validations are successful, it will attempt to determine the action being performed, ie create or update and based on that action, it will use urlRoot and call the appropriate REST API. perform the operation.

var Book = Backbone.Model.extend({
    defaults: {
        ID: "",
        BookName: ""
    },
    idAttribute: "ID",
    initialize: function () {
        console.log('Book has been initialized');
        this.on("invalid", function (model, error) {
            console.log("Houston, we have a problem: " + error)
        });
    },
    constructor: function (attributes, options) {
        console.log('Book\'s constructor had been called');
        Backbone.Model.apply(this, arguments);
    },
    validate: function (attr) {
        if (attr.ID <= 0) {
            return "Invalid value for ID supplied."
        }
    },
    urlRoot: 'http://localhost:51377/api/Books'
}); 

var book = new Book({ BookName: "Backbone Book 43" });
book.save({}, {
    success: function (model, response, options) {
        console.log("The model has been saved to the server");
    },
    error: function (model, xhr, options) {
        console.log("Something went wrong while saving the model");
    }
});

All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí