backbone入门系列(2)模型

首先看MVC中的M,model模型。

创建模型方法

var Note=Backbone.Model.extend({}),当使用extend时,有一个参数时,设置的为实例方法,存在第二个可选属性时,设置的是静态方法,区别就是前者需要new实例化,后者直接可以调用。

模型实例化

在模型中有各种参数

defaults:默认值,在其中可以为model设置各种一开始就有的值。

initialize:初始化,在其中可以添加一开始就有的方法

validate:验证,在其中设置规则,运行过程中如果涉及到就会有相关反应

各种事件及绑定

object.on(event, callback, [context])

var Note=Backbone.Model.extend({ //new Note()
defaults:{
title:'llll',
time:new Date()

},initialize:function(){
console.log("新创建了一次"+this.get("title"));
this.on("change",function(model,option){
console.log("有东西改变了")
});
this.on ("change:title",function(model,option){
console.log('标题改变了')
})

},validate:function(attribute,options){
if(attribute.title.length<3){
return "笔记字数过短"
}
}//当使用验证功能时,要给set等方法使用第三个参数validate:true
});

控制台

原文地址:https://www.cnblogs.com/cumting/p/6854973.html