对于Ext.data.Store 介紹 与总结,以及对以前代码的重构与优化

来源:互联网 发布:科鲁兹方向机在线编程 编辑:程序博客网 时间:2024/05/18 19:37

     对于Ext.data.Store 一直不是很了解,不知道他到底是干嘛的有哪些用处,在实际开发中也由于不了解也走了不少弯路,

store是一个为Ext器件提供record对象的存储容器,行为和属性都很象数据表.

由于刚学不是太懂,都是比葫芦画瓢,东搬西畴的去完成功能.程序思路都是自己想象的,对于rest方式的增删改查全是采用另外一种方式去实现的,最后研究发现其实,store都

已经有了这些函数,根本不用自己去实现.下面看下以前所写的代码:这是model,store ,gridpanel

var store;Ext.onReady(function () {    //接口管理model    Ext.define('InterfaceModel', {        extend: 'Ext.data.Model',        fields: [{            name: 'ID',            type: 'int',            useNull: true        }, 'FunctionCode', 'FunctionName', 'IsEnabled', 'Invoker', 'Module'],        validations: [{            type: 'length',            field: 'FunctionCode',            min: 1        }, {            type: 'length',            field: 'FunctionName',            min: 1        }, {            type: 'length',            field: 'Invoker',            min: 1        }]        //        proxy: {        //            type: 'rest',        //            url: 'api/InterfaceManage'        //        }    });    //接口数据加载    store = Ext.create('Ext.data.Store', {        autoLoad: true,        autoSync: true,        pageSize: 20,        model: 'InterfaceModel',        proxy: {            type: 'rest',            url: 'api/InterfaceManage',            reader: {                type: 'json',                root: 'Data',                totalProperty: 'TotolRecord'            },            writer: {                type: 'json'            }        }    });    //删除单条接口信息    function OnDelete(id) {        $.ajax({            type: 'DELETE',            url: '/api/InterfaceManage/' + id,            data: {},            contentType: "application/json; charset=utf-8",            dataType: 'json',            success: function (results) {                store.load();            }        })    }    //单选checkbox模式    var selModel = Ext.create('Ext.selection.CheckboxModel', {        width: 55,        injectCheckbox: 1,        listeners: {            selectionchange: function (sm, selections) {                grid.down('#removeButton').setDisabled(selections.length === 0);                grid.down('#editButton').setDisabled(selections.length === 0);            }        }    });    //接口数据渲染    var grid = Ext.create('Ext.grid.GridPanel', {        id: 'node_Interface',        width: 400,        height: 300,        frame: true,        title: '接口管理',        store: store,        iconCls: 'icon-user',        selModel: selModel,        border: false, //grid的边界         listeners: {            itemdblclick: function (grid, rowIndex, e) {                var record = grid.getSelectionModel().getSelection()[0];                if (record) {                    UpdateInterface();                    //更新功能                    Ext.getCmp('BtnSave_newsinfo').on('click', function () {                        OnUpdate(record.get('ID'));                    });                    Ext.getCmp('code').setValue(record.get('FunctionCode'));                    Ext.getCmp('name').setValue(record.get('FunctionName'));                    Ext.getCmp('isEnable').setValue(record.get('IsEnabled'));                    Ext.getCmp('Invoker').setValue(record.get('Invoker'));                    Ext.getCmp('Module').setValue(record.get('Module'));                }                else {                    Ext.Msg.alert('提示', '请选择要编辑的内容');                }            }        },        columns: [Ext.create('Ext.grid.RowNumberer', { width: 35, text: '序号' }), {            text: '编号',            width: 40,            sortable: true,            hideable: false,            dataIndex: 'ID'        }, {            text: '接口代码',            width: 80,            sortable: true,            dataIndex: 'FunctionCode',            field: {                xtype: 'textfield'            }        }, {            header: '接口名称',            width: 120,            sortable: true,            dataIndex: 'FunctionName',            field: {                xtype: 'textfield'            }        }, {            text: '是否启用',            width: 80,            // xtype: 'checkcolumn',            dataIndex: 'IsEnabled',            renderer: function boolFromValue(val) {                if (val) {                    return '<img src=../../Content/images/true.png>'                }                else {                    return '<img src=../../Content/images/false.png>'                }            }        }, {            text: '调用者',            width: 100,            sortable: true,            dataIndex: 'Invoker',            field: {                xtype: 'textfield'            }        }, {            text: '所属模块',            width: 100,            sortable: true,            dataIndex: 'Module',            field: {                xtype: 'textfield'            }        }],        bbar: Ext.create('Ext.PagingToolbar', {            plugins: [new Ext.ux.ComboPageSize({})],            store: store, //---grid panel的数据源            displayInfo: true,            displayMsg: '显示 {0} - {1} 条,共计 {2} 条',            emptyMsg: "没有数据"        }),        dockedItems: [{            xtype: 'toolbar',            items: [{                text: '添加',                iconCls: 'icon-add',                handler:                function () {                    AddInterface();                    store.reload();                }            }, '-', {                itemId: 'removeButton',                text: '删除',                iconCls: 'icon-delete',                disabled: true,                handler: function () {                    var selection = grid.getSelectionModel().getSelection();                    var len = selection.length;                    if (len == 0) {                        Ext.Msg.alert('提示', '请先选择要删除的数据');                    }                    else {                        Ext.Msg.show({                            title: '系统确认',                            msg: '你是否确定删除这些数据!',                            buttons: Ext.Msg.YESNO,                            scope: this,                            fn: function (btn) {                                if (btn == 'yes') {                                    for (var i = 0; i < len; i++) {                                        var id = selection[i].get('ID');                                        OnDelete(id);                                        //console.log(selection[i]);                                        //store.remove(selection[i]);                                    }                                }                            }, icon: Ext.MessageBox.QUESTION                        });                    }                }            }, '-', {                itemId: 'editButton',                text: '编辑',                disabled: true,                iconCls: 'icon-edit',                handler:                             function () {                                 var record = grid.getSelectionModel().getSelection()[0];                                 if (record) {                                     UpdateInterface();                                     //更新功能                                     Ext.getCmp('BtnSave_newsinfo').on('click', function () {                                         OnUpdate(record.get('ID'));                                     });                                     Ext.getCmp('code').setValue(record.get('FunctionCode'));                                     Ext.getCmp('name').setValue(record.get('FunctionName'));                                     Ext.getCmp('isEnable').setValue(record.get('IsEnabled'));                                     Ext.getCmp('Invoker').setValue(record.get('Invoker'));                                     Ext.getCmp('Module').setValue(record.get('Module'));                                 }                                 else {                                     Ext.Msg.alert('提示', '请选择你要编辑的内容');                                 }                             }            }]        }]    });

添加函数

// Copyright : 欧蓝德畅电子技术有限公司.  All rights reserved.// 文件名:AddInterfac.js// 文件描述:添加接口信息//-----------------------------------------------------------------------------------// 创建者:李勇// 创建时间:2013-06-20//====================================================================================Ext.require([    'Ext.form.*',    'Ext.layout.container.Absolute',    'Ext.window.Window']);var win;//窗口function  AddInterface() {    var form = Ext.create('Ext.form.Panel', {                border: false,        bodyPadding: 20,        border: 1, //边框        frame: true, //        defaults: {//统一设置表单字段默认属性            //autoFitErrors : false,//展示错误信息时是否自动调整字段组件宽度            labelSeparator: ':', //分隔符            labelWidth: 100, //标签宽度            width: 350, //字段宽度            allowBlank: false, //是否允许为空            blankText: '不允许为空', //若设置不为空,为空时的提示            labelAlign: 'right', //标签对齐方式            msgTarget: 'qtip'          //显示一个浮动的提示信息            //msgTarget :'title'       //显示一个浏览器原始的浮动提示信息            //msgTarget :'under'       //在字段下方显示一个提示信息            //msgTarget :'side'        //在字段的右边显示一个提示信息            //msgTarget :'none'        //不显示提示信息            //msgTarget :'errorMsg'    //在errorMsg元素内显示提示信息        },        items: [{            xtype: 'textfield',            fieldLabel: '接口代码',            id: 'code',            anchor: '90%'        },                        {                            xtype: 'textfield',                            fieldLabel: '接口名称',                            id:'name',                            name:'name',                            anchor: '90%'                        },                        {                            xtype: 'checkbox',                                                      fieldLabel: '是否启用',                            boxLabel: '',                            id: 'isEnable',                            anchor: '90%'                        },                        {                            xtype: 'textfield',                            fieldLabel: '调 用 者',                            id: 'Invoker',                            anchor: '90%'                        },                        {                            xtype: 'textfield',                            fieldLabel: '所属模块',                            id: 'Module',                            anchor: '90%'                        }           ]    });     win = Ext.create('Ext.window.Window', {        autoShow: true,        title: '接口添加',        width: 400,        height: 250,        minWidth: 300,        minHeight: 200,        buttonAlign: 'center',        modal: true,        resizable: false,        layout: 'fit',        plain: true,        items: form,        buttons: [{            text: '确定',            handler: function () {                OnInsert();            }        }, {            text: '取消',            handler: function () {                win.close();            }        }]    });};//添加接口函数function OnInsert(evt) {    var functionCode = Ext.getCmp('code').getValue();    var FunctionName = Ext.getCmp('name').getValue();    var IsEnabled = Ext.getCmp('isEnable').getValue();    var Invoker = Ext.getCmp('Invoker').getValue();    var module = Ext.getCmp('Module').getValue();    var data = '{"ID":"' + '' + '","FunctionCode":"' + functionCode + '","FunctionName":"' + FunctionName + '","IsEnabled":"' + IsEnabled + '","Invoker":"' + Invoker + '","Module":"' + module + '"}';    $.ajax({        type: 'POST',        url: '/api/InterfaceManage',        data: data,        contentType: "application/json; charset=utf-8",        dataType: 'json',        success: function (results) {            Ext.Msg.alert('添加提示', '添加成功!');            store.reload();            win.close();        }    })}

修改函数:

// Copyright : 欧蓝德畅电子技术有限公司.  All rights reserved.// 文件名:UpdateInterface.js// 文件描述:更新接口信息//-----------------------------------------------------------------------------------// 创建者:李勇// 创建时间:2013-06-20//====================================================================================Ext.require([    'Ext.form.*',    'Ext.layout.container.Absolute',    'Ext.window.Window']);var win;function UpdateInterface() {    var form = Ext.create('Ext.form.Panel', {        border: false,        bodyPadding: 20,        border: 1, //边框        frame: true, //        defaults: {//统一设置表单字段默认属性            //autoFitErrors : false,//展示错误信息时是否自动调整字段组件宽度            labelSeparator: ':', //分隔符            labelWidth: 120, //标签宽度            width: 350, //字段宽度            allowBlank: false, //是否允许为空            blankText: '不允许为空', //若设置不为空,为空时的提示            labelAlign: 'right', //标签对齐方式            msgTarget: 'qtip'          //显示一个浮动的提示信息            //msgTarget :'title'       //显示一个浏览器原始的浮动提示信息            //msgTarget :'under'       //在字段下方显示一个提示信息            //msgTarget :'side'        //在字段的右边显示一个提示信息            //msgTarget :'none'        //不显示提示信息            //msgTarget :'errorMsg'    //在errorMsg元素内显示提示信息        },        items: [{            xtype: 'textfield',            fieldLabel: '接口代码',            id: 'code',            anchor: '90%'        },                        {                            xtype: 'textfield',                            fieldLabel: '接口名称',                            id: 'name',                            name: 'name',                            anchor: '90%'                        },                        {                            xtype: 'checkbox',                            fieldLabel: '是否启用',                            boxLabel: '',                            id: 'isEnable',                            anchor: '90%'                        },                        {                            xtype: 'textfield',                            fieldLabel: '调 用 者',                            id: 'Invoker',                            anchor: '90%'                        },                        {                            xtype: 'textfield',                            fieldLabel: '所属模块',                            id: 'Module',                            anchor: '90%'                        }           ]    });    win = Ext.create('Ext.window.Window', {        autoShow: true,        title: '接口更新',        width: 400,        height: 250,        resizable: false,        buttonAlign: 'center',        minWidth: 300,        minHeight: 200,        layout: 'fit',        plain: true,        items: form,        modal: true,        buttons: [{            text: '更新',            id: 'BtnSave_newsinfo'        }, {            text: '取消',            handler: function () {                win.close();            }        }]    });};//更新数据function OnUpdate(id) {    //获取要更新的数据    var functionCode = Ext.getCmp('code').getValue();    var FunctionName = Ext.getCmp('name').getValue();    var IsEnabled = Ext.getCmp('isEnable').getValue();    var Invoker = Ext.getCmp('Invoker').getValue();    var module = Ext.getCmp('Module').getValue();    var data = '{"ID":"' + id + '","FunctionCode":"' + functionCode + '","FunctionName":"' + FunctionName + '","IsEnabled":"' + IsEnabled + '","Invoker":"' + Invoker + '","Module":"' + module + '"}';    $.ajax({        type: 'PUT',        url: '/api/InterfaceManage/' + id,        data: data,        contentType: "application/json; charset=utf-8",        dataType: 'json',        success: function (results) {            Ext.Msg.alert('提示', '更新成功!');            store.reload();            win.close();        }    })}

删除函数,包含到上面那部分代码中了.下面我们一步一步来优化代码:

  1. 修改删除函数:
    原先的OnDelete函数全部去掉,在相应的删除事件中添加

    store.remove(selection[i]);

    这样他就会自动调用rest对应的delete方式,将要删除的对象传到后台.还没完,使用OnDelete函数传到后台的是id,而使用remove传到后台的是model对象,所以后台

    接受的参数需要进行相应的改变.

  2. 修改添加函数:去掉了重新写的往后台传值方式,直接调用Rest的Post方式,修改后的OnInsert函数如下:
    //添加接口函数function OnInsert(evt) {    var functionCode = Ext.getCmp('code').getValue();    var FunctionName = Ext.getCmp('name').getValue();    var IsEnabled = Ext.getCmp('isEnable').getValue();    var Invoker = Ext.getCmp('Invoker').getValue();    var module = Ext.getCmp('Module').getValue();    var newInterfaceModel = new InterfaceModel(    {        ID: '',        FunctionCode: functionCode,        FunctionName: FunctionName,        IsEnabled: IsEnabled,        Invoker: Invoker,        Module: module        });    store.insert(0, newInterfaceModel);    store.reload();    win.close();}

    这种方式直接调用store的insert()方法,insert方法所对应的就是post方式.



  3. 对update函数的修改:


<script type="text/javascript"><!--google_ad_client = "ca-pub-1944176156128447";/* cnblogs 首页横幅 */google_ad_slot = "5419468456";google_ad_width = 728;google_ad_height = 90;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>