Backbone.js的Model

Backbone.js的Model的教程

  • 扩展model
    var M = Backbone.Model.extend({
        aaa: function(){  //实例方法
            alert('123');
        }
       },{
            bbb: function(){ //静态方法
                alert('456');
            }
    });
    
    var model = new M();
    model.aaa();
    M.bbb();
  • get()和set()方法
    var model = new Backbone.Model();
    model.set('name','hello');
    alert(model.get('name'));
    
  • 默认赋值
    var M = Backbone.Model.extend({
        defaults:{
            name:'hello'
        }
    });
    var model = new M;
    alert(model.get('name'));
  • 继承
    var M = Backbone.Model.extend({
        aaa: function(){
            alert(123);
        }
    });
    var childM = M.extend();
    var model = new childM;
    model.aaa();
  • 自定义事件
    var M = Backbone.Model.extend({
        defaults:{
            name:'jason'
        },
        initialize: function(){     //初始化构造函数
            this.on('change', function(){
                alert('changed');
            });
        }
    });
    var model = new M;
    model.set('name','Agnes');   //触发change事件
  • 自定义事件 - 针对某个具体属性
    var M = Backbone.Model.extend({
        defaults:{
            name:'jason',
            age: 12
        },
        initialize: function(){     //初始化构造函数
            this.on('change:name', function(model){  //可以传入model参数
                alert('name changed');
                console.log(model);
            });
        }
    });
    var model = new M;
    model.set('name','Agnes');   //触发change事件
    model.set('age',15);
    
  • model和view的绑定
    var M = Backbone.Model.extend({
        defaults:{
            name:'jason'
        }
    });
    var V = Backbone.View.extend({
        initialize: function(){
            //当实例中传入的model发生改变的时候,调用show()方法
            this.listenTo(this.model,'change',this.show);
        },
        show: function(model){
            $('body').append('<div>'+model.get('name')+'</div>');
        }
    });
    var m = new M;
    var v = new V({model:m});  //以字典的方式传入model的实例,完成model和view的绑定
    m.set('name','Agnes');         //触发change事件 调用了show方法