1. 程式人生 > 其它 >對於Ext.data.Store 介紹 與總結,以及對以前程式碼的重構與優化

對於Ext.data.Store 介紹 與總結,以及對以前程式碼的重構與優化

     對於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函式全部去掉,在相應的刪除事件中新增 這樣他就會自動呼叫rest對應的delete方式,將要刪除的物件傳到後臺.還沒完,使用OnDelete函式傳到後臺的是id,而使用remove傳到後臺的是model物件,所以後臺 接受的引數需要進行相應的改變.
store.remove(selection[i]);
  1. 修改新增函式:去掉了重新寫的往後臺傳值方式,直接呼叫Rest的Post方式,修改後的OnInsert函式如下: 這種方式直接呼叫store的insert()方法,insert方法所對應的就是post方式.
//新增介面函式
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();
}
  1. 對update函式的修改: