重庆熊猫 Loading

ExtJS-Data Package (数据处理包) Model类型

更新记录
2023年3月9日 抽取模型间的关系为单独章节。
2023年3月3日 优化结构,添加更多的说明。
2022年7月7日 发布。
2022年7月6日 从笔记迁移到博客。

ExtJS教程汇总:https://www.cnblogs.com/cqpanda/p/16328016.html

Ext.data.Model(模型)

模型说明

模型通常从Ext.data.Model类继承,类似:域模型(Domain)、实体(Entity)
例如:商城系统中可能有 用户(User)、产品(Product) 和 订单(Order) 的模型

Model和数据库的关系:
Ext.data.Model类结构和SQL中的表结构类似
每个Ext.data.Model类的实例表示一条数据库SQL记录

在模型中:
使用Ext.data.Association类描述模型与模型之间的关系
使用Ext.data.Validations类用来设置模型的数据验证
使用Ext.data.Reader类用来将数据读入DataStore数据集
使用Ext.data.Writer类将DataStore中的数据写回到服务器中

image

模型内定义了:

字段(Fields)、字段类型(Field types)
数据验证(Validation)
模型关联(Associations)
代理(Proxy)
架构(Schema)

注意:如果指定的字段(fields)没有定义类型,则将使用默认类型“auto”
注意:代理(Proxy)在可以数据存储(DataStore)中指定,也可以在模型中指定
注意:架构(schema)是应用程序中所有模型的管理器

创建模型

说明

通过继承Ext.data.Model类型实现自定义模型类型
通过Ext.create()方法创建自定义模型实例
使用get()方法设置模型实例中的数据
使用set()方法读取模型实例中的数据

模型文件存放位置

模型存放位置:app -> model

image

读取/设置模型实例数据

//读取
var lastName = newEmployee.get('lastName');
//设置
newEmployee.set('gender','Female');

设置模型字段验证

具体的验证类型包括:
presence: 确保字段必须有值。在这里,0是合法值,而空字符串不是。
length:确保字符串值的长度符合要求。需要使用min和max两个验证属性来:定义最小长度和最大长度。
format:确保值符合规定的格式。该验证使用正则表达式来定义格式,需要在matcher验证属性中定义格式的正则表达式。
inclusion:值必须在指定的值列表内。需要使用list验证属性来定义值列表,值列表是 由可选值组成的数组。
exclusion:值不能是值列表中的值。与inclusion一样,要使用list来定义值列表。

在模型内定义验证器

validators: {
    //单个验证条件
    '字段名称': '验证类型',
    //多个验证条件
    '字段名称': { 验证类型: '验证类型值', ...}
}

实例:

fields:[
    { name: 'website' , type: 'string' },
    { name: 'status'  , type: 'string' },
    { name: 'clientSince' , type: 'date', dateFormat: 'Y-m-d H:i' }
],
validators:{
    name:[
        { type:'presence'}
    ],
    website:[
        { type:'presence', allowEmpty:true},
        { type:'length',  min: 5, max:250 }
    ]
}

模型类型的实例,可以使用isValid()方法,检测模型中的数据是否满足验证条件:

modelInstance.isValid()

设置排序方式

sorters配置项即可
注意:一般在Store中设置sorters

sorters: [
    {
        property: 'firstname',
        direction: 'ASC'
    }
],

设置代理

使用proxy配置项即可,但一般在Store中定义代理

设置自动加载

关闭自动加载数据

autoLoad: false,

开启自动加载数据

autoLoad: true,

设置代理并加载数据

Model也可以设置proxy,并且可以加载数据
与Store不同处在于,Model加载的数据只有1条,Store是表示多条数据的集合

配置代理使用Model的proxy配置项即可
加载数据使用Model的静态load方法即可

//定义User模型
Ext.define('PandaApp.model.User', {
    extend: 'Ext.data.Model',
    idPropery: 'id',
    fields: [
        { name: 'id', type: 'int' },
        { name: 'name', type: 'string' }
    ],
    proxy: {
        url: '/user.json',
        type: 'ajax',
        model: 'PandaApp.model.User',
        reader: {
            type: 'json'
        }
    }
});

//使用静态方法加载数据
PandaApp.model.User.load(666, {
    success: function(record){
        console.log('success');
        console.log(record.get('id'));  //666
        console.log(record.get('name')); //panda
    },
    failure: function(record, operation) {
        console.log('failure');
    },
    callback: function(record, operation, success) {
        console.log('callback');
    }
});

设置Id键默认值

说明

使用identifier配置项即可
ExtJS支持三类Id默认值方式:

Ext.data.identifier.Sequential    //顺序增长
Ext.data.identifier.Negative      //逆向增长
Ext.data.identifier.Uuid          //UUID

按顺序增长

Ext.define('MyApp.data.MyModel', {
    extend: 'Ext.data.Model',
    requires: ['Ext.data.identifier.Sequential'],
    identifier: 'sequential',
    //...
});

逆序增长

Ext.define('MyApp.data.MyModel', {
    extend: 'Ext.data.Model',
    requires: ['Ext.data.identifier.negative'],
    identifier: 'negative',
    //...
});

使用UUID

Ext.define('MyApp.data.MyModel', {
    extend: 'Ext.data.Model',
    requires: ['Ext.data.identifier.Uuid'],
    identifier: 'uuid',
    //...
 });

还可以更细致的配置

Ext.define('MyApp.data.MyModel', {
    extend: 'Ext.data.Model',
    identifier: {
        type: 'sequential', //类型
        seed: 1000,         //起始
        prefix: 'ID_'       //前缀
    }
});

实例(Model配置)

实例:创建最简单的模型

创建继承自Ext.data.Model类型的自定义类型即可

Ext.define('PandaApp.model.EmployeeModel', {
    extend: 'Ext.data.Model'
    //...
});

实例:指定模型的Id字段

使用idProperty配置项即可

Ext.define('PandaApp.model.User', {
    extend: 'Ext.data.Model',
    idProperty: 'UserId',
    //...
});

实例:自动生成id字段的值

使用identifier配置项

Ext.define('PandaApp.model.Boss', {
    extend: 'Ext.data.Model',
    idProperty: 'Id',
    fields: [
        { name: 'Id', type: 'int' },
        { name: 'Name', type: 'string' }
    ],
    identifier: {  //自动生成id字段的值
        type: 'uuid'  //设置生成uuid
    }
});

实例:定义字段(字符串形式)

使用fields配置项即可
注意:这样定义的字段的类型默认为auto类型
注意:如果不定义id字段,将会自动定义一个id字段

Ext.define('Panda.model.Employee', {
    extend: 'Ext.data.Model',
    fields: [
        'name', 'email', 'phone'
    ]
});

实例:定义自定义字段(对象形式)

Ext.define('PandaApp.model.User', {
    extend: 'Ext.data.Model',
    idProperty: 'UserId',
    fields: [
        { name: 'UserId', type: 'int' },
        { name: 'UserName', type: 'string' },
        { name: 'Age', type: 'int' }
    ]
});

实例:定义字段映射

后端传来的字段可以和Model中定义的字段名称不同
使用映射就可以了

//定义Model
Ext.define('PandaApp.model.PandaModel', {
    extend: 'Ext.data.Model',
    idProperty: 'id',
    fields: [
        { name: 'id', tpye: 'int' },
        //这里定义了映射
        { name: 'name', type: 'string', mapping:'fullName' }
    ]
});

//创建Store实例
var pandaStore = Ext.create('Ext.data.Store', {
    model: 'PandaApp.model.PandaModel',
    proxy: {
        type: 'ajax',
        url: '/test.json',
        reader: {
            type:'json',
            rootProperty: 'data',
            idProperty: 'id',
        }
    }
});

pandaStore.load({   //加载数据
    callback: function(records, operation, successful){
        if(successful)
        {
            var data = this.first();
            console.log(data.get('fullName')); //原始字段可以访问
            console.log(data.get('name'));     //映射的字段也可以访问
        }
        else
        {
            console.log('服务器错误');
        }
    }
});

实例:定义数值字段并设置默认值

Ext.define('PandaApp.model.User', {
    extend: 'Ext.data.Model',
    idProperty: 'UserId',
    fields: [
        { name: 'UserId', type: 'int' },
        { name: 'PandaValue', type: 'float', defaultValue:99.99 },
        { name: 'Age', type: 'int', defaultValue:18 },
    ]
});

实例:定义日期字段并设置格式

Ext.define('PandaApp.model.User', {
    extend: 'Ext.data.Model',
    idProperty: 'UserId',
    fields: [
        { name: 'UserId', type: 'int' },
        { name: 'UserName', type: 'string' },
        { name: 'Age', type: 'int' },
        //日期字段
        { name: 'CreateDateTime', type: 'date', dateFormat: 'Y-m-d H:i' }
    ]
});

实例:配置Model-配置proxy

注意:Model也可以配置代理,只不过只能代表一条数据

Ext.define('BizDash.model.Sale', {
    extend: 'Ext.data.Model',
    proxy: {   //定义代理
        type : 'ajax',
        url : 'sale.json',
        reader: {
            type: 'json'
        }
    }
});

实例:定义应用使用的基类Model

//定义模型基类
Ext.define('PandaApp.model.Base', {
    extend: 'Ext.data.Model',
    //定义字段
    fields: [
        { name: 'id', type: 'int'}
    ],
    //定义架构
    schema: {
        namespace: 'PandaApp.model',  //默认的命名空间
        // Ext.util.ObjectTemplate
        proxy: {                        //设置代理
            type: 'ajax',               //设置代理的类型为ajax
            url: '{entityName}.json',   //设置请求的url
            reader: {                   //设置读取器
                type: 'json',
                rootProperty: '{entityName:lowercase}'
            }
        }
    }
});

//继承模型基类
Ext.define('PandaApp.model.SomeModel', {
    extend: 'PandaApp.model.Base',
});

实例:从自定义的应用基类模型继承

Ext.define('PandaApp.model.Person', {
    extend: 'PandaApp.model.Base',
    fields: [
        'name', 'email', 'phone'
    ]
});

实例:指定模型的id字段

Ext.define('PandaApp.model.Student', {
    extend: 'Ext.data.Model',
    idProperty:'Id',
    fields: [     // 字段
        { name: 'Id', type: 'int' },
        'firstName',
        'lastName'
    ]
});

定义模型依赖项

Ext.define('myApp.model.Customer',{
    extend: 'Ext.data.Model',
    requires: [ 'myApp.model.Contract' ], //定义依赖项
    idProperty: 'id',
    fields: [  //定义字段
        { name: 'id', type: 'int' },
        { name: 'name', type: 'string' },
        { name: 'phone', type: 'string' },
        { name: 'website', type: 'string' },
        { name: 'status', type: 'string' },
        { name: 'clientSince', type: 'date', dateFormat: 'Y-m-d H:i' },
        { name: 'country', type: 'string' },
        { name: 'sendnews', type: 'boolean' },
        { name: 'employees', type: 'int' },
        { name: 'contractInfo', reference: 'Contract', unique:true } //定义一对一关联
    ]
});

实例:定义模型相关联的proxy、schema

Ext.define('PandaApp.model.Base', {
    extend: 'Ext.data.Model',
    idProperty: 'Id',
    schema: {
        namespace: 'PandaApp.model',
        proxy: {
            
        }
    }
});

实例:定义字段、自动加载、排序、代理

Ext.define('PandaApp.model.Base', {
    extend: 'Ext.data.Model',
    stores: {
        employee: {
            fields: [
                { name: 'id', type: 'string' },
                { name: 'firstname', type: 'string' },
                { name: 'lastname', type: 'string' }
            ],
            autoLoad: false,
            sorters: [
                {
                    property: 'firstname',
                    direction: 'ASC'
                }
            ],
            proxy: {
                type: 'rest',
                url: 'employee',
                reader: {
                    type: 'json',
                },
                writer: {
                    type: 'json'
                }
            }
        }
    }
});

实例(Model增删改查)

实例:定义模型的实例(直接实例化)(直接初始化数据)

//定义模型
Ext.define('PandaApp.model.User', {
    extend: 'Ext.data.Model',
    idProperty: 'UserId',
    fields: [
        { name: 'UserId', type: 'int' },
        { name: 'UserName', type: 'string' },
        { name: 'Age', type: 'int' },
        //日期字段
        { name: 'CreateDateTime', type: 'date', dateFormat: 'Y-m-d H:i' }
    ]
});

//创建实例
var obj = Ext.create('PandaApp.model.User', {
    UserId: '666',
    UserName: 'panda666',
    Age: 666666,
    CreateDateTime: "2020-10-21 18:18"
});

console.log(obj.get('UserId')); //666
console.log(obj.get('UserName')); //panda666
console.log(obj.get('Age')); //666666
console.log(obj.get('CreateDateTime')); //Wed Oct 21 2020 18:18:00 GMT+0800
console.log(obj.isValid()); //true

实例:定义模型的实例(直接实例化)(使用set初始化数据)

//定义模型
Ext.define('PandaApp.model.User', {
    extend: 'Ext.data.Model',
    idProperty: 'UserId',
    fields: [
        { name: 'UserId', type: 'int' },
        { name: 'UserName', type: 'string' },
        { name: 'Age', type: 'int' },
        //日期字段
        { name: 'CreateDateTime', type: 'date', dateFormat: 'Y-m-d H:i' }
    ]
});

//创建实例
var obj = Ext.create('PandaApp.model.User');
obj.set('UserId',"666");
obj.set('UserName',"panda666");
obj.set('Age',"666666");
obj.set('CreateDateTime',"2020-10-21 18:18");

备注:还可以使用set一次性设置多个字段值

实例:模型实例读取/写入数据-使用get/set

var newEmployee = Ext.create('Panda.model.Employee', {
    id: 1,
    firstName: 'Shiva',
    lastName: 'Kumar',
    fulltime: true,
    gender: 'Male',
    phoneNumber: '123-456-7890'
});

//读取get
var lastName = newEmployee.get('lastName');
//设置set
newEmployee.set('gender','Female');

//设置后记得用.commit();方法进行提交修改。

实例:新建/删除数据到后端服务器

实例来自官方文档。

Ext.define('MyApp.model.User', {
    extend: 'Ext.data.Model',
    fields: [
        {name: 'id', type: 'int'},
        {name: 'name', type: 'string'}
    ],
    proxy: {
        type: 'ajax',
        url: 'server.url'
    }
});

var user = new MyApp.model.User({
    name: 'Foo'
});

// pass the phantom record data to the server to be saved
user.save({
    success: function(record, operation) {
        // do something if the save succeeded
        // erase the created record
        record.erase({
            failure: function(record, operation) {
                // do something if the erase failed
            },
            success: function(record, operation) {
                // do something if the erase succeeded
            },
            callback: function(record, operation, success) {
                // do something if the erase succeeded or failed
            }
        });
    }
});

实例:提交修改

model.commit();

实例:使用set方法一次性设置多个值

//定义模型
Ext.define('PandaApp.model.User', {
    extend: 'Ext.data.Model',
    idProperty: 'UserId',
    fields: [
        { name: 'UserId', type: 'int' },
        { name: 'UserName', type: 'string' },
        { name: 'Age', type: 'int' },
        //日期字段
        { name: 'CreateDateTime', type: 'date', dateFormat: 'Y-m-d H:i' }
    ]
});

//创建实例
var obj = Ext.create('PandaApp.model.User');

//使用set一次性设置多个字段
obj.set({
    UserId: '666',
    UserName: 'panda666',
    Age: 666666,
    CreateDateTime: "2020-10-21 18:18"
});

//验证是否有效数据
console.log(obj.isValid());

实例:模型实例读取/写入数据-使用data属性

注意:优先使用get和set方法,而不是直接操作data属性

//定义模型
Ext.define('PandaApp.model.User', {
    extend: 'Ext.data.Model',
    idProperty: 'UserId',
    fields: [
        { name: 'UserId', type: 'int' },
        { name: 'UserName', type: 'string' },
        { name: 'Age', type: 'int' },
        //日期字段
        { name: 'CreateDateTime', type: 'date', dateFormat: 'Y-m-d H:i' }
    ]
});

//创建实例
var obj = Ext.create('PandaApp.model.User', {
    UserId: '666',
    UserName: 'panda666',
    Age: 666666,
    CreateDateTime: "2020-10-21 18:18"
});

//使用data访问值
console.log(obj.data.UserId); //666
console.log(obj.data.UserName); //panda666
console.log(obj.data.Age); //666666
console.log(obj.data.CreateDateTime); //Wed Oct 21 2020 18:18:00 GMT+0800

//使用data设置值
obj.data.UserId = 888;
obj.data.UserName = 'dog';
obj.data.Age = 88888;
obj.data.CreateDateTime = '2020-10-21 16:16';

console.log(obj.data.UserId); //666
console.log(obj.data.UserName); //panda666
console.log(obj.data.Age); //666666
console.log(obj.data.CreateDateTime); //Wed Oct 21 2020 18:18:00 GMT+0800

//验证是否有效数据
console.log(obj.isValid());

实例:定义模型验证(实例化模型)(验证数据)

//定义模型
Ext.define('PandaApp.model.Test',{
    extend: 'Ext.data.Model',
    fields: [
        { name:'id', type:'int' },
        { name:'name',tyle:'string' }
    ],
    validators: {
        id:'presence',
        name: {type:'length',min: 3 }
    }
});

//创建实例
var studentData = Ext.create('Student',{
    id:666,
    name:'panda'
});

//验证模型的数据是否有效
if(studentData.isValid())
{
    var id = studentData.get('id');
    var name = studentData.get('name');
    console.log(id);
    console.log(name);
}
else
{
    console.log('student data is not valid');
}

实例:模型数据写入到localstorage

//定义User模型
Ext.define('PandaApp.model.User', {
    extend: 'Ext.data.Model',
    idPropery: 'id',
    fields: [
        { name: 'id', type: 'int' },
        { name: 'name', type: 'string' }
    ],
    proxy: {
        id: 'user',
        type: 'localstorage',
        model: 'PandaApp.model.User',
        reader: {
            type: 'json'
        }
    }
});

//创建实例
var instance1 = Ext.create('PandaApp.model.User', {
    id: '888',
    name: 'Dog'
});
//保存数据
instance1.save();

//创建实例
var instance2 = Ext.create('PandaApp.model.User', {
    id: '999',
    name: 'Monkey'
});
//保存数据
instance2.save();
从localstorage读取模型数据
//定义User模型
Ext.define('PandaApp.model.User', {
    extend: 'Ext.data.Model',
    idPropery: 'id',
    fields: [
        { name: 'id', type: 'int' },
        { name: 'name', type: 'string' }
    ],
    proxy: {
        id:'user',
        type: 'localstorage',
        model: 'PandaApp.model.User',
        reader: {
            type: 'json'
        }
    }
});

//使用静态方法加载数据
PandaApp.model.User.load(888, {
    success: function(record){
        console.log('success');
        console.log(record.get('id'));  //888
        console.log(record.get('name')); //dog
    },
    failure: function(record, operation) {
        console.log('failure');
    },
    callback: function(record, operation, success) {
        console.log('callback');
    }
});

//使用静态方法加载数据
PandaApp.model.User.load(666, {
    success: function(record){
        console.log('success');
        console.log(record.get('id'));  //666
        console.log(record.get('name')); //panda
    },
    failure: function(record, operation) {
        console.log('failure');
    },
    callback: function(record, operation, success) {
        console.log('callback');
    }
});
posted @ 2022-07-07 09:24  重庆熊猫  阅读(297)  评论(0编辑  收藏  举报