重庆熊猫 Loading

ExtJS-数据处理-Store自身数据读写实例

更新记录
2022年7月17日 发布。
2022年7月6日 从笔记迁移到博客。

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

Store自身数据读写实例

实例:读取数据-本地数组数据

使用Store实例的loadData()方法即可

//测试用的数组数据
var data = [
    ['Panda', 666],
    ['Dog', 222],
    ['Monkey', 888]
];

//定义模型
Ext.define('PandaApp.model.User',{
    extend: 'Ext.data.Model',
    fields: [
        //字段名称           //数据类型      //与数据的对应关系
        { name: 'UserName', type: 'string', mapping: 1 },
        { name: 'age', type: 'int', mapping: 2 }
    ]
});

//测试用的Store
var pandaStore = Ext.create('Ext.data.Store',{
    model: 'PandaApp.model.User',            //指定模型的类型
    proxy: {
        type: 'memory',                     //代理的类型:内存
        reader: {                           //定义读取器
            type: 'array',                  //指定读取器的类型
            model: 'PandaApp.model.User'    //指定模型的类型
        }
    }
});

//加载数据到Store中
pandaStore.loadData(data);
//获得第一行数据
console.log(pandaStore.first().data);

实例:读取数据-后端JSON数据

配置好参数,使用load方法即可

测试使用的JSON格式:

{
    "data" : [
        {
            "id" : "1",
            "name" : "Accounting",
            "dateActive" : "12/01/2001",
            "numEmployees" : "45"
        }
    ],
    "meta" : {
        "success" : true,
        "msg" : "This Data Is Get Success"
    }
}

//新建Store
var employeeStore = Ext.create('Ext.data.Store',{
    fields: [    //设置Model的字段
        { name: 'id', type: 'int' },
        'name',
        'dateActive',
        'numEmployees'
    ],
    proxy:{     //设置代理的类型
        type: 'ajax',        //请求的类型
        url: 'test.json',    //请求数据的来源
        reader: {            //数据读取器JsonReader
            type: 'json',          //数据的类型
            rootProperty: 'data',  //JSON数据中的根节点名称
            idProperty: 'id',      //数据的id列名称
            successProperty: 'meta.success'  //JSON数据中成功指示节点名称
        }
    }
});

//加载数据
employeeStore.load({
    callback: function(records, operation, successful){
        if(successful)
        {
            console.log('获得数据成功');
            //遍历读取所有记录
            Ext.each(records, function(record, index){
                //处理单独的记录数据
                console.log(record.get('name'));
                console.log(record.get('dateActive'));
                console.log(index);
            });
        }
        else
        {
            console.log('服务器错误');
        }
    }
});

实例:读取数据-后端XML数据

配置好参数,使用load方法即可
测试使用的XML格式:

<?xml version="1.0" encoding="UTF-8" ?>
<Response>
    <data>
        <node>
            <id>1</id>
            <name>Panda666</name>
            <dateActive>12/01/2022</dateActive>
            <numEmployees>45</numEmployees>
        </node>
    </data>
    <meta>
        <success>true</success>
        <msg>This Is Message</msg>
    </meta>
</Response>
//新建Store
var employeeStore = Ext.create('Ext.data.Store',{
    fields: [    //设置Model的字段
        {
            name: 'id',
            type: 'int'
        },
        'name',
        'dateActive',
        'numEmployees'
    ],
    proxy:{     //设置代理
        type: 'ajax',        //设置代理请求的类型
        url: 'test.xml',     //请求数据的来源
        reader: {            //数据读取器
            type: 'xml',     //数据的类型
            record: 'node',  //XML数据中的根节点名称
            idPath: 'id',    //XML数据的id列名称
            successProperty: 'meta/success'  //XML数据中成功指示节点名称
        }
    }
});

employeeStore.load({   //加载数据
    callback: function(records, operation, successful){
        if(successful)
        {
            console.log('获得数据成功');
            //输出数据
            console.log(records[0]);
        }
        else
        {
            console.log('服务器错误');
        }
    }
})

实例:读取数据-手动加载数据存储的数据

手动加载存储以接收一组MyApp.model.User记录
然后,当触发存储加载的回调函数时(完成时),记录这些记录

var store = new Ext.data.Store ({
    model: 'MyApp.model.User'
});

store.load({
    callback:function(){
        var first_name = this.first().get('name');
         console.log(first_name);
    }
});

实例:写入数据-调用sync同步数据到服务器端

当所有同步操作都已完成且没有任何异常或失败时,将调用success方法
如果同步中的一个或多个操作失败,将调用failure方法
在同步操作完成时将调用callback方法,无论其成功与否
注意:sync方法还有一个params附加属性,可以使用它在同步期间传递任何附加参数
注意:sync会进行批处理(batch operation)操作,会同时发送多条HTTP请求

store.sync({
    callback: function (batch, options) {
        //Do something
    },
    success: function (batch, options) {
        //Do something
    },
    failure: function (batch, options) {
        //Do something
    },
    scope: this
});

实例:写入数据-增删改查

使用writer可以节省时间和精力,无需再编写Ajax请求和异常处理
要使用Writer,需要配置数据存储以及支持的代理
要创建一个配置对象api用于对接后端的增删改查操作

//定义测试用的模型
Ext.define('PandaApp.model.PandaModel', {
    extend: 'Ext.data.Model',
    fields: [
        { name: 'id', type: 'int' },
        { name: 'name', type: 'string' },
        { name: 'isActive', type: 'bool' },
        { name: 'dateActive' ,type: 'date' },
        { name: 'description', type: 'string' },
        { name: 'employeeCode', type: 'string' }
    ]
});

//定义测试用的Store
Ext.define('PandaApp.store.PandaStore', {
    extend: 'Ext.data.Store',
    model: 'PandaApp.model.PandaModel', //关联的Model
    autoLoad: false,  //关闭自动加载
    autoSync: false,   //关闭自动同步
    proxy: {    //定义代理
        type: 'ajax',
        url: '/index.php',
        api: {    //定义增删改查API
            create : '/index.php?action=create',  //增
            destroy: '/index.php?action=remove',  //删
            update:  '/index.php?action=update',  //改
            read:    '/index.php?action=read'     //查
        },
        actionMethods:{   //定义动作对应的HTTP方法
            create: 'POST',
            read: 'POST',
            update: 'POST',
            destroy: 'POST'
        },
        reader: {  //定义读取器
            type: 'json',
            rootProperty:'data',
            idProperty: 'id',  //设置数据的Id列
            successProperty: 'meta.success', //设置成功检测位字段
            totalProperty: 'meta.total', //设置数据条数字段
        },
        writer: {  //定义写入器
            type: 'json',
            rootProperty: 'data',
            encode: true,
            allowSingle: false,
            writeAllFields: false,  //写入所有属性,实际环境中设置为false
            batch: false,
            successProperty: 'meta.success' //设置成功检测位
        }
    }
});

//防抄 panda666  666 panda

//实例化数据仓库
var store = Ext.create('PandaApp.store.PandaStore');

//=========================读取数据(加载数据)=========================
store.load({    //这会触发read操作
    callback: function(records, operation, successful){
        if(successful)
        {
            console.log('获得数据成功');
            //遍历读取所有记录
            Ext.each(records, function(record, index){
                //处理单独的记录数据
                console.log(record.get('name'));
                console.log(record.get('dateActive'));
                console.log(index);
            });
            console.log(store.count());
        }
        else
        {
            console.log('服务器错误');
        }
    }
});
//=========================读取数据(加载数据)=========================

//=========================修改数据=========================
var updateRecord = store.getAt(0);
updateRecord.set('employeeCode','888');
console.log(updateRecord);
//注意:
//  如果开启了autoSync,这里使用beginEdit和endEdit
//  updateRecord.beginEdit();
//  updateRecord.set('employeeCode','888');
//  updateRecord.endEdit();
//  这样就不用再调用sync了
//  如果没有开启autoSync,则需要调用sync方法
//=========================修改数据=========================

//=========================添加数据=========================
var modelInstance1 = Ext.create('PandaApp.model.PandaModel', {
    'id': 3698,
    'name': 'jame',
    'isActive': true,
    'dateActive': '2020/10/23',
    'description': 'this is add data',
    'employeeCode': '3698'
});
var modelInstance2 = Ext.create('PandaApp.model.PandaModel', {
    'id': 3888,
    'name': 'jame',
    'isActive': true,
    'dateActive': '2020/10/23',
    'description': 'this is add data',
    'employeeCode': '3888'
});
//写入数据
store.add([modelInstance1, modelInstance2]);
//同步到后端
store.sync();
//=========================添加数据=========================

//=========================删除数据=========================
var deleteRecord = store.getAt(0);
store.remove(deleteRecord);
store.sync();
//=========================删除数据=========================
实例:写入数据-localstorage
//定义model
Ext.define('PandaApp.model.User', {
    extend: 'Ext.data.Model',
    idProperty: 'Id',
    fileds: [
        { name: 'Id', tpye: 'int' },
        { name: 'Name', type: 'string' }
    ]
});

//定义localstorage Store
Ext.define('PandaApp.store.Users', {
    extend: 'Ext.data.Store',
    model: 'PandaApp.model.User',
    proxy: {
        type: 'localstorage',
        id : 'users'
    }
});

//创建实例
var instance = Ext.create('PandaApp.store.Users');

//添加数据
var user1 = Ext.create('PandaApp.model.User', {
    Id: '666',
    Name: 'Panda'
});
instance.add(user1);

console.log(instance);

//同步数据
instance.sync({
    success: function(){
        console.log('sync success');
    },
    failure: function(){
        console.log('sync failure');
    }
});
posted @ 2022-07-17 07:58  重庆熊猫  阅读(409)  评论(0编辑  收藏  举报