backbone 之数据模型

  Model在Backbone中为数据模型,是一个基础,最根本的基类,用于原始数据,底层方法的封装和定义。

一 、创建一个简单模型对象

1 创建一个简单模型对象

 var student = Backbone.Model.extend({
   initialize: function () {
     intNum++;
     console.log("您构建了" + intNum + "个对象");
   }
 });
var intNum = 0;
 var stuA = new student();
 var stuB = new student();

2 对象模型的赋值方法

 var student = Backbone.Model.extend({
   initialize: function () {

   }
       defaults: {
                Code: "",
                Name: "",
                Score: ""
       }
 });
var stuA = new student();
stuA.set({
    Code: "10105",
    Name: "陆明明",
     Score: "300"
});
console.log(stuA.get("Name") + " 在 " + stuA.get("Class") + " 读小学");
console.log(stuA.escape("Name") + " 在 " + stuA.escape("Class") + " 读小学");

 

3 自定义Printlog方法

 var student = Backbone.Model.extend({
   initialize: function () {

   }
       defaults: {
                Code: "",
                Name: "",
                Score: ""
       }
        PrintLog: function () {
            console.log(stuA.get("Name") + " 在 " + stuA.get("Class") + " 读小学");
            console.log(stuA.escape("Name") + " 在 " + stuA.escape("Class") + " 读小学");
        }
 });


var stuA = new student();
stuA.set({
    Code: "10105",
    Name: "陆明明",
     Score: "300"
}); 
stuA.PrintLog();                   

 

4. 监听Name属性值的变化

var student = Backbone.Model.extend({
    initialize: function () {
//                初始化时监听属性值变化事件
        this.on("change:Name", function (model, value) {
            var oldname = model.previous("Name");
            var newname = value;
            if (oldname != newname) {
                console.log("Name原值:" + oldname + ",新值:" + newname);
      }
});
            },
            defaults: {
            Code: "",
            Name: "ABC",
            Score: ""
       }
}); 
var stuA = new student();
stuA.set("Name", "CBD");

 

二、模型对象

2.1 读取数据

5. 调用get方法获取对象指定的对象值

 1 var student = Backbone.Model.extend({
 2     default: {
 3         Code:"",
 4         Name:"",
 5         Score:""
 6     }    
 7 });
 8 var stuA = new student({
 9         Code:"10103",
10         Name:"李时华",
11         Score:""    
12 });
13 console.log("学号:" + stuA.get("Code") +
14             "姓名:" + stuA.get("Name") +
15             "性别:" + stuA.get("Sex") +
16             "分数:" + stuA.get("Score"));

 

 

2.2 修改数据

6. set方法批量重置默认属性值

var student = Backbone.Model.extend({
    default: {
        Code:"",
        Name:"",
        Score:""
    }    
});
var stuA = new student({
        Code:"10104",
        Name:"周小敏",
        Score:"500"    
});
var stuB = new student();
stuB.set({
        Code:"10105",
        Name:"陆明明",
        Score:"300"        
});
console.log("1. 学号:" + stuA.get("Code") +
            "   姓名:" + stuA.get("Name") +
            "   分数:" + stuA.get("Score"));
console.log("2. 学号:" + stuB.get("Code") +
            "   姓名:" + stuB.get("Name") +
            "   分数:" + stuB.get("Score"));

 

2.3 开启数据验证

7.开启数据验证

var student = Backbone.Model.extend({
    initialize:function(){
        this.on('invalid',function(model,error){
            console.log(error)
        });
    },
    validate: function(attrs){
        if (!_.isString(attrs.Name) return '姓名必须是自负'
        if (!_.isNumber(attrs.Score)) return '分数必须是数字!')
    },
    default: {
        Code:"10001",
        Name:"张三",
        Score:"100"
    }    
});

var stuE = new student();
stuE.set({
        Code:"10105",
        Name: 12345,
        Score: 600        
}, {"validate": true});
console.log(stuE.toJSON());

 

2.4 关闭数据验证

8.关闭数据验证

var student = Backbone.Model.extend({
    initialize:function(){
        this.on('invalid',function(model,error){
            console.log(error)
        });
        this.on('change:Name',function(model,value){
            console.log("你触发了Name属性修改事件!")
        });
    },
    validate: function(attrs){
        if (!_.isString(attrs.Name) return '姓名必须是自负'
        if (!_.isNumber(attrs.Score)) return '分数必须是数字!')
    },
    default: {
        Code:"10001",
        Name:"张三",
        Score:"100"
    }    
});

var stuE = new student();
stuE.set({
        Code:"10105",
        Name: 12345,
        Score: 600        
}, {"silent:": true});
console.log(stuE.toJSON());

 

2.5 更新数据回滚

9 更新数据回滚

var student = Backbone.Model.extend({
    initialize:function(){
        this.on('invalid',function(model,error){
            console.log(error)
        });
        this.on('change:Name',function(model,value){
            console.log("你触发了Name属性修改事件!")
        });
    },
    validate: function(attrs){
        if (!_.isString(attrs.Name) return '姓名必须是自负'
        if (!_.isNumber(attrs.Score)) return '分数必须是数字!')
    },
    default: {
        Code:"10001",
        Name:"张三",
        Score:"100"
    }    
});

var stuE = new student();
stuE.set({
        Code:"10105",
        Name: 12345,
        Score: 600        
}, {"silent:": true});
console.log(stuE.toJSON());
if (!_.isString(stuE.get("Name")) !_.isNumber(stuE.get("Score"))) {
    setE.set({"Name":stuE.previous("Name"),
    "Score": stuE.previous("Score")});
}
console.log(stuE.toJSON());

 

2.6 删除数据

10 调用unset方法删除指定属性的数据

var student = Backbone.Model.extend({
    initialize:function(){

    },
    default: {
        Code:"10106",
        Name:"李小明",
        Score:650
    }    
});

(stuE.unset("Name");
console.log(stuE.get("Name"));
console.log(stuE.toJSON());
stuE.set("Name", stuE.previous("Name"));
console.log(stuE.toJSON());
stuE.clear();
console.log(stuE.toJSON());

 

三、对象属性操作

3.1 attributes对象

11 调用attributes对象获取全部的属性值

var student = Backbone.Model.extend({
    initialize:function(){

    },
    default: {
        Code:"10001",
        Name:"张三",
        Score:100
    }    
});
var setE  = new student();
stuE.set({
        Code:"10106",
        Name:"李小明",
        Score:650    
});

console.log(stuE.attributes);
var attrs =stuE.attributes;
for (var i in attrs) {
    console.log(i + ":" + stuE.attributes[i]);
}

 

3.2 previous和previousAttributes方法

12 调用previousAttributes方法返回数据

var student = Backbone.Model.extend({
    initialize:function(){

    },
    default: {
        Code:"10001",
        Name:"张三",
        Score:100
    }    
});
var setE  = new student();
stuE.set({
        Code:"10106",
        Name:"李小明",
        Score:650    
});

console.log(stuE.toJSON());
console.log(stuE.previousAttributes());
console.log("------");
stuE.set({
        Code:"10107",
        Name:"陈天豪",
        Score: 720    
});

console.log(stuE.toJSON());
console.log(stuE.previousAttributes());

 

3.3 set内部顺序

a. key 或value生成对象

b. 初始化option选项

c. 调用_validate 方法执行验证

d. 调用unset方法删除属性

e. 执行静默方式重置数据

四、同步数据到服务器

4.1 save方法

13 使用save方法发送数据

var student = Backbone.Model.extend({
    initialize:function(){

    },
    url:"/ch4/api/save.php"
    default: {
        Code:"10001",
        Name:"张三",
        Score:100
    }    
});
var setE  = new student();
stuE.set({
        Code:"10107",
        Name:"陶国荣",
        Score: 750        
});
stuE.save();

 

14 使用save方法接收数据

var student = Backbone.Model.extend({
    initialize:function(){

    },
    url:"/ch4/api/save.php"
    default: {
        Code:"10001",
        Name:"张三",
        Score:100
    }    
});
var setE  = new student();
stuE.set({
        Code:"10107",
        Name:"陶国荣",
        Score: 750        
});
stuE.save(null, {
    success: function (model, response) {
        console.log(response.code);
    }
});

 

15 使用save方法时设置wait属性

var student = Backbone.Model.extend({
    initialize:function(){

    },
    url:"/ch4/api/save.php"
    default: {
        Code:"10001",
        Name:"张三",
        Score:100
    }    
});
var setE  = new student();
stuE.set({
        Code:"10107",
        Name:"陶国荣",
        Score: 750        
}, {success: function (model, response) {
    console.log(response);
}, wait: true
});
console.log(stuE.toJSON());

 

4.2 fetch方法

16 使用fetch方法获取服务器数据

var student = Backbone.Model.extend({
    initialize:function(){

    },
    url:"/ch4/api/save.php"    
});
var setE  = new student();
stuE.fetch({
    success: function (model, response) {
        console.log(stuE.toJSON());
    }, 
    error: fun(ction(error) {
            console.log("err");
    }
});

 

4.3 destory 方法

17 使用destroy方法从服务器删除数据

var student = Backbone.Model.extend({
    initialize:function(){
        this.on('destroy', function() {
            console.log('正在调用destroy方法');
        });
    },
    url:"/ch4/api/destroy.php",
    idAttribute:"Code"
});
var setE  = new student({
    Code: "10107"
});
stuE.destroy({
    success: function (model, response) {
        if (response.code == "0") {
            console.log("Code为" + model.get("Code") + "的数据已删除")
        }
    }, 
    error: fun(ction(error) {
            console.log("删除数据出现异常");
    },
    wait:true
});

小结:

1. 模型封装了对象数据,并提供了一系列对数据进行操作的方法

2. 我们可以在定义模型类、实例化模型对象、和调用set()方法来设置模型中的数据

3. 当模型中数据发生改变时,会触发change事件和属性事件

4. 我们可以定义validate方法对模型中的数据进行验证

通过调用save()、fetch()和destroy()方法可以让模型中的数据与服务器保持同步,但在此之前必须设置url或urlRoot属性

posted on 2016-06-17 11:16  nap  阅读(399)  评论(0编辑  收藏  举报