模型类(Ext.data.Model)是data包的核心部件。每个模型代表应用程序中的一些数据类型。可以将model看成表结构,定义model就是定义表结构。
1定义一个数据模型
<span style="font-size:12px;">Ext.define('Information',{ //定义一个'Information'类,继承自Ext.data.Model
extend: 'Ext.data.Model',
fields: [//定义拥有的字段
{name: 'first' },//字段名:first,类型:auto(默认)
{name:'last' },
{name: 'age', type: 'int' }, //字段名:age,类型:int
{name: 'birthday', type:'date'}, //字段名:birthday,类型:date,指定日期格式为:'日/月/年'
{name: 'isStudent', type:'boolean', defaultValue: false } //字段类型:boolean,指定字段默认值为false
]
});</span>
2.使用模型类
模型类通常在存储类中使用,这些存储类是一些模型实例的集合。设置存储类和加载他的数据如下:
<span style="font-size:12px;">Ext.create('Ext.data.Store', {
model: 'Information',
proxy:{
type:'ajax', //使用Ajax代理配置存储类,告诉它加载的url地址
url:'user.json',
reader: 'json' //解码数据的读取器,服务器返回JSON格式数据
},
autoLoad: false
});</span>
3.为model对象添加自定义方法
<span style="font-size:12px;">Ext.define('Information',{ //定义一个'Information'类,继承自Ext.data.Model
extend: 'Ext.data.Model',
fields: [
{name: 'first' },
{name:'last' },
{name: 'age', type: 'int' },
{name: 'birthday', type: 'date'},
{name: 'isStudent', type:'boolean', defaultValue: false }
],
getInformation:function () {
var info=”名字:”+this.get(‘first’)+”.”+this.get(‘last’)+”;年龄:”+this.get(‘age’)+”;日:”+this.get(‘birthday’);
Ext.Msg.alert("基本信息",info);
}
});</span>
//创建一条数据,数据结构为'Information'
<span style="font-size:12px;">var me=Ext.ModelManager.create({
first: 'Ed',
last: 'Spencer',
age: '30',
birthday: '2012/4/4'
}, 'Information');
//执行自定义方法
me.getInformation();</span>
4.模型之间的关联
模型之间可以相互关联。例如官网给的一个读书例子,一本书可以有多个评论。
每个模型类可以和其他模型类有任意多的关联,这将使得应用程序中的复杂关系变得简单。一旦建立一个模型实例,可以很轻松遍历相关的数据,如:
//加载使用id =1和相关的评论
<span style="font-size:12px;">Book.load(1,{
success:function(book){
book.reviews().each(function(review){
//省略.....操作
});
}
});</span>