一、模型 - Model
1.創建一個空的Note模型
var Note = Backbone.Model.extend({});
2.實例化Note模型
1).實例化一個空的模型
var note1 = new Note()
2).實例化模型並添加屬性
var note2 = new Note({
title: 'backbone學習筆記',
created_at: new Date()
});
3.模型的操作方法
1).獲取屬性值
note2.attributes;
note2.toJSON(); //返回來一個對象
JSON.stringify(note2); //返回json格式數據
2).返回對象集合中是否包含指定的key值,包含返回true,否則返回false
note2.has('title');
3).獲取指定屬性的值
note2.get('title'); // 返回title屬性的值
4).刪除指定屬性的值
note2.unset('title');
5).設置指定屬性的值 有此屬性時,更改值,沒有時添加此屬性和值
note2.set('title', 'backbone學習筆記');
6).清空對象中所有的屬性
note2.clear();
4.設置模型的默認屬性
var Note = Backbone.Model.extend({
defaults: {
title: '',
created_at: new Date()
}
});
5.模型的初始化
initialize: 此方法在實例化時立即調用
var Note = Backbone.Model.extend({
defaults: {
title: '',
created_at: new Date()
},
initialize: function() {
console.log('新創建了一條筆記:' + this.get('title'));
}
});
6.屬性發生變化時,觸發的事件change
var Note = Backbone.Model.extend({
defaults: {
title: '',
created_at: new Date()
},
initialze: function() {
console.log('新創建了一條筆記:' + this.get('title'));
this.on('change', function(model, options) {
console.log('屬性的值發生了變化');
});
this.on('change:title', function(model, options) {
console.log('title 屬性發生了變化');
});
}
});
7.驗證屬性的值 validate
attributes: 對象屬性
options: 選項的參數
var Note = Backbone.Model.extend({
defaults: {
title: '',
created_at: new Date()
},
initialize: function() {
console.log('新創建一條筆記:' + this.get('title'));
this.on('change', function(model, options) {
console.log('屬性的值發生了變化');
});
this.on('change:title', function(model, options) {
console.log('title 屬性發生了變化');
});
},
validate: function(attributes, options) {
if (attributes.title.length < 3) {
return '筆記的標題字符數要大於3';
}
}
});
8.驗證失敗後的事件 invalid
model:對象
error:錯誤信息
var Note = Backbone.Model.extend({
defaults: {
title: '',
created_at: new Date()
},
initialize: function() {
console.log('新創建了一條筆記:' + this.get('title'));
this.on('change', function(model, options) {
console.log('屬性的值發生了變化');
});
this.on('change:title', function(model, options) {
console.log('title 屬性發生了變化');
});
this.on('invalid', function(model, error) {
console.log(error);
});
},
validate: function(attributes, options) {
if (attributes.title,length < 0) {
return '筆記的標題字符要大於3';
}
}
});