Part 2:Understanding the baics of Backbone Models


もっと読む
When we talk about any MV*pattern,model isundoubtedy the most impopopopopopopotantpartof the architecture/aplication.Itsthe model that contains all the aappcacation data.Along with keeping the the datatitititititititititititititititititititit the the the the the datatatatatatatatatatata momomomomotititititititititititititititiaaaapas.aaaaaapas the momomomomomomomomomomomomomost the data,defining access to various parts of data contained in the model.
Backbone.js models are also the most importent building blocks when it commes to building backbone.js appication.It keeps track data、perform validations on and provide a mechanger thereeigerウェブサイト
Link to compleete series:
  • Part 1:Introduction to Backbone.Js
  • Part 2:Understanding the baics of Backbone Models
  • Part 3:More about Backbone Models
  • Part 4:CRUD Operations on BackboneJs Models using HTTP REST Service
  • Part 5:Understanding Backbone.js Collection
  • Part 6:Understanding Backbone.js View
  • Part 7:Understanding Backbone.js Routes and History
  • Part 8:Understanding Backbone.js Events
  • Creating a simple backbone.js Model
    To create a backbone model,we simply need to exted the backbone model class.Follwing code snippet shows how this can be done.
    var Book = Backbone.Model.extend({
       
    });
    Futher more、if we want to create a model that inhers from our model class then we just need to exted from model class.
    var ChildrensBook = Book.extend({
       
    });
    Instantiating a Model
    Backbone models can simply be instantiated by using the new keyword.
    var book = new Book();
    Deleting a model
    To delete a model,we just need to call the destroy function on the model.
    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 caled when the model get success deleted.
    book.destroy({
        success: function () {
            alert("The model has been destroyed successfully");
        }
    });
    Clong 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 cal the clone method.
    function cloneModel() {
        var book = new Book();
    
        var book2 = book.clone();
    }
    How to specify the model atributes
    Backbone models does not enforce defining the atributes in the model definition itself i.e.one can create a model and specife the atributes on the fly.Lets want to create 2 atributes the motrek.Bots.
    var book = new Book({
        ID: 1,
        BookName: "Sample book"
    });
    Default values of model atributes
    Now creating the atributes on the fly supported by the backbone models and it is a very powerful feature.But this feature actually becompes proves to be a mantnance nintmate when it commit to working with langer appece apple.apple.apple.apple.apple.I would like the possibility to define my models atributes in my model definition itself.
    To accomplaish this,the default function can be used.The default function is used to specify the default atributes of the model and the the ir default values.Lets try to move the motributes the modefinition.
    var Book = Backbone.Model.extend({
        defaults: {
            ID: "",
            BookName: ""
        },    
    });
    This way just instantiating the model will be enough and the created models will have these atributes assited with them.
    Setting and getting model atributes
    Oneed 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 atribute existence
    Since backbone allows us to add atributes on the fly,we need some way to identify whether a particular atribute exist in the model or not.To do this we can the has function model.
    book.has('ID');     // true
    book.has('author');  // false
    Defining Funtions in a Model
    We can also define our functions in the model clases.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 atribute changes
    Wen can also use e the events to listen to the model chages.Thiscan be done by listening to the change event.backbone Lises a change event whenever any model atribute ischaged.For aaatetribute atribute wet bute bute wen caststststststststaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaatststststsaaaaaaaaaaaaatetetetetetetetetetetetetetetetetetetetetetetetetetetetetetetetetetetetetemodel changen our current model.
    [size=large]
    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'));
        }
    });
    [/size]
    If we have a lot of atributes and we are interested in listening to change for any specific atribute then perhaps we can specify that to to int binding.Lets try to listen to the Bookme 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
    Sotte that is for this blog.the idea behind this article was to get familier with the baic concepts of the backbone model.In next article of this series,we will look at the advanced topics the spect the the the pertrantiness born
    原文のリンク:http://rahulrajatsingh.com/2014/07/backbone-tutorial-part-2-understanding-the-basics-of-backbone-models/
  • backboneModelsSampleApp.zip(127.3 KB)
  • ダウンロード回数:0