ExtJS使用入门

来源:互联网 发布:数据采集与处理杂志 编辑:程序博客网 时间:2024/06/12 23:55

我们这个项目组最近大概大家都很忙!

前几天把项目用到的ssi框架都基本看完了,整天也不知道做什么,我的无聊大概也是被我们组的主管给发现了,

于是,主管就给分派了个任务:使用ext的grid写一个表格,能够读取和显示本地数据:json、array、xml

然后要能修改 新增 和删除等功能,具体细节自己脑补!

当时还没听你搞清楚,听了个est……百度给纠正的……

于是,接下来感觉自己有事情做了真爽,各种查资料与观看源代码。终于在这个过程中知道了ext是个什么东西,因为一直听jquery……所以就感觉好像它也不是那么难嘛!

建议先去下个源码文件,我自己下的 3.3的 在这里:http://download.csdn.net/detail/my_silence_time/5763329,4.0的那个太大上传不了,就偷懒了!

如果要查看docs,最好下个小型服务器LiteServer(我自己用这个):http://download.csdn.net/detail/my_silence_time/5763265  已注册

不然要每次都打开tomcat确实不爽。

我是先看的examples,在里面找了好多例子看了看,另外 ,我其实以前不太熟悉javaScript,虽然用过,但是根本就没有系统的去看过,只是自己照猫画虎的每次在页面里写个验证的方法之类的,所以我直接把学习javascript的决心给转移到了ext里面  。。

下面是我弄的代码,我准了一个简单的电话本:

先看Html:

<html><head>    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    <title>个人通讯录</title>    <!-- ** CSS ** -->    <!-- base library -->    <link rel="stylesheet" type="text/css" href="ext/resources/css/ext-all.css" />    <!-- overrides to base library -->    <!-- page specific -->    <link rel="stylesheet" type="text/css" href="ext/examples.css" />    <link rel="stylesheet" type="text/css" href="ext/grid-examples.css" />    <link rel="stylesheet" type="text/css" href="ext/RowEditor.css" />    <!--<style type=text/css>        /* style rows on mouseover */        .x-grid3-row-over .x-grid3-cell-inner {            font-weight: bold;        }        /* style for the "buy" ActionColumn icon */        .x-action-col-cell img.buy-col {            height: 16px;            width: 16px;            background-image: url(../shared/icons/fam/accept.png);        }        /* style for the "alert" ActionColumn icon */        .x-action-col-cell img.alert-col {            height: 16px;            width: 16px;            background-image: url(../shared/icons/fam/error.png);        }    </style>   -->    <!-- ** Javascript ** -->    <!-- ExtJS library: base/adapter -->    <script type="text/javascript" src="ext/ext-base.js"></script>    <!-- ExtJS library: all widgets -->    <script type="text/javascript" src="ext/ext-all.js"></script>    <!-- overrides to base library -->    <!-- page specific -->    <script type="text/javascript" src="array-grid.js"></script>    <script type="text/javascript" src="ext/RowEditor.js"></script></head><body>    <h1>SimpleComtacts_ByArray</h1>    <p>这是一个简单的WEB通讯录</p>    <p>Note that the js is not minified so it is readable. See <a href="array-grid.js">array-grid.js</a>.</p>    <!-- add Contacts-->    <div id="grid">            </div></body></html>
其中ext-all.css和ext-all.js、ext-base.js是必须要引入的.array-grid.js是我的js文件,别的根据需要自己看着办吧 ……还是得查资料……

array-grid.js文件:

/*! * Ext JS Library 3.3.0 * Copyright(c) 2006-2010 Ext JS, Inc. * licensing@extjs.com * http://www.extjs.com/license */Ext.onReady(function(){    Ext.QuickTips.init();    // NOTE: This is an example showing simple state management. During development,    // it is generally best to disable state management as dynamically-generated ids    // can change across page loads, leading to unpredictable results.  The developer    // should ensure that stable state ids are set for stateful components in real apps.        Ext.state.Manager.setProvider(new Ext.state.CookieProvider());    // sample static data for the store    var myData = [        ['11101', '边宇坤', 'man',  '13880116582',  'description'],        ['12234', 'xxx', 'woman',  '13880116582',  'description'],        ['12233', 'eee', 'man',  '13880116582',  'description'],        ['15432', 'trt', 'man',  '13880116582',  'description'],        ['17890', 'yyy', 'man',  '13880116582',  'description'],        ['16543', 'qqq', 'woman',  '13880116582',  'description'],        ['14332', 'iii', 'man',  '13880116582',  'description'],        ['13321', 'ooo', 'man',  '13880116582',  'description'],        ['16664', 'ttt', 'man',  '13880116582',  'description'],        ['19999', 'kkk', 'man',  '13880116582',  'description'],            ];    /**     * Custom function used for column renderer     * @param {Object} val     */    // function change(val) {    //     if (val > 0) {    //         return '<span style="color:green;">' + val + '</span>';    //     } else if (val < 0) {    //         return '<span style="color:red;">' + val + '</span>';    //     }    //     return val;    // }    // *    //  * Custom function used for column renderer    //  * @param {Object} val         // function pctChange(val) {    //     if (val > 0) {    //         return '<span style="color:green;">' + val + '%</span>';    //     } else if (val < 0) {    //         return '<span style="color:red;">' + val + '%</span>';    //     }    //     return val;    // }    // create the data store    var store = new Ext.data.ArrayStore({        fields: [           {name: 'id', type:'string'},           {name: 'name',      type:'string'},           {name: 'gender',     type:'string'},           {name: 'phone',  type:'string'},           {name: 'desc', type:'string'}        ]    });    var Contact = Ext.data.Record.create([{        name: 'id',        type: 'string'    }, {        name: 'name',        type: 'string'    }, {        name: 'gender',        type: 'string'    },{        name: 'phone',        type: 'string'    },{        name: 'desc',        type: 'string'    }]);    // manually load local data    store.loadData(myData);    // create the columnModel    // var sm = new Ext.grid.CheckboxSelectionModel();     // var cm = new Ext.data.ColumnModel([    // new Ext.grid.RowNumberer(), //自动行号    // sm,   //多选框    //         {    //             id       :'id',    //             header   : '编号',     //             width    : 75,     //             sortable : true,     //             dataIndex: 'id'    //         },    //         {    //             header   : '姓名',     //             width    : 100,     //             sortable : true,     //             // renderer : 'usMoney',     //             dataIndex: 'name'    //         },    //         {    //             header   : '性别',     //             width    : 75,     //             sortable : true,     //             // renderer : change,     //             dataIndex: 'gender'    //         },    //         {    //             header   : '电话号码',     //             width    : 100,     //             sortable : true,     //             // renderer : pctChange,     //             dataIndex: 'phone'    //         },    //         {    //             header   : '其他',     //             width    : 200,     //             sortable : true,     //             // renderer : Ext.util.Format.dateRenderer('m/d/Y'),     //             dataIndex: 'desc'    //         }    // ]);function changeSex(value){    if (value == 'man') {        return "<span style='color:red;font-weight:bold;'>"+value+"</span>";    } else {        return "<span style='color:green;font-weight:bold;'>"+value+"</span>";    }}    // create the Grid    var sm = new Ext.grid.CheckboxSelectionModel();     // var editor = new Ext.ux.grid.RowEditor({    //     saveText:'Update'    // });    var grid = new Ext.grid.EditorGridPanel({        store: store,        sm:sm,        // plugins: [editor],        // view: new Ext.grid.GroupingView({        //     markDirty: false        // }),        // colunms : cm ,        columns: [            new Ext.grid.RowNumberer(), //自动行号            sm,            {                // id       :'id',                header   : '编号',                 width    : 75,                 sortable : true,                 dataIndex: 'id',                editor:{                    xtype: 'textfield',                    allowBlank: false                }            },            {                header   : '姓名',                 width    : 100,                 sortable : true,                 // renderer : 'usMoney',                 dataIndex: 'name',                editor: {                    xtype: 'textfield',                    allowBlank: false                }            },            {                header   : '性别',                 width    : 75,                 sortable : true,                 renderer : changeSex,                 dataIndex: 'gender',                editor: {                    xtype: 'textfield',                    allowBlank: false                }            },            {                header   : '电话号码',                 width    : 100,                 sortable : true,                 // renderer : pctChange,                 dataIndex: 'phone',                editor: {                    xtype: 'textfield',                    allowBlank: false                }            },            {                header   : 'Description',                 width    : 200,                 sortable : true,                 // renderer : Ext.util.Format.dateRenderer('m/d/Y'),                 dataIndex: 'desc',                editor: {                    xtype: 'textfield',                    allowBlank: false                }            },            {                xtype: 'actioncolumn' ,                header : "操作",                width: 50,                items:[                {                    icon: 'ext/delete.gif' ,   //Use a URL in the icon config                    tooltip : "删除信息" ,                    handler: function(grid,rowIndex,colIndex){    //这是个固定的格式   这个函数与 xtype=‘actionColumn相配合’ 可以添加图片按钮                         // Ext.MessageBox.confirm('消息', '确认要删除所选记录?');                         // var record = grid.getStore().getAt(rowIndex);                         // alert('show','当前选中的数据是'+record.get('name'));                        Ext.MessageBox.confirm('删除','确认要删除所选记录?',callBack);                         function callBack(btn){                            if(btn == 'yes'){                                var record =grid.getStore().getAt(rowIndex);                                grid.getStore().remove(record);                                // grid.getView().refresh();                                                           }                         }                     }                                    },                // {                //     icon: 'ext/save.gif' ,    //这里是更新数据                //     tooltip: "edit" ,                // }                ]            }            ],        bbar: new Ext.PagingToolbar({          pageSize: 10,          store: store,          displayInfo: true,          displayMsg: '显示第 {0} 条到 {1} 条记录,一共 {2} 条',          emptyMsg: "没有记录"          }) ,        clickToEdit : 1,                tbar:new Ext.Toolbar({            items:[            {                id:"newContacts",                text :"新建联系人",                handler: function(){                    var cont = grid.getStore().recordType;                    var c = new cont({                        id:'00000',                        name:'……',                        gender:'……',                        phone:'……',                        desc:'……',                    });                    grid.stopEditing();                    store.insert(0,c);                    grid.startEditing(0,0);                                    }            },                "-",                // "->",            {                id:"deleteMany",                text:"批量删除" ,                handler:function(){                     var selModel = grid.getSelectionModel();                      if (selModel.hasSelection()) {                          Ext.Msg.confirm("警告", "确定要删除吗?", function(button) {                              if (button == "yes") {                                  var selections = selModel.getSelections();                                  Ext.each(selections, function(item) {                                      store.remove(item);                                  });                              }                          });                      }                      else {                          Ext.Msg.alert("错误", "没有任何行被选中,无法进行删除操作!");                      }                  }            }            ]}),            // {            //     xtype: 'actioncolumn',            //     width: 50,            //     items: [{            //         icon   : '../shared/icons/fam/delete.gif',  // Use a URL in the icon config            //         tooltip: 'Sell stock',            //         handler: function(grid, rowIndex, colIndex) {            //             var rec = store.getAt(rowIndex);            //             alert("Sell " + rec.get('company'));            //         }            //     }, {            //         getClass: function(v, meta, rec) {          // Or return a class from a function            //             if (rec.get('change') < 0) {            //                 this.items[1].tooltip = 'Do not buy!';            //                 return 'alert-col';            //             } else {            //                 this.items[1].tooltip = 'Buy stock';            //                 return 'buy-col';            //             }            //         },            //         handler: function(grid, rowIndex, colIndex) {            //             var rec = store.getAt(rowIndex);            //             alert("Buy " + rec.get('company'));            //         }            //     }]            // }                        stripeRows: true,        // autoExpandColumn: 'id',        autoHeight: true ,        // height : 350 ,        width : 600 ,        title: 'Contacts',        // config options for stateful behavior        stateful: true,        stateId: 'grid',            });    // render the grid to the specified div in the page    grid.render('grid');       });

这个是我的最终给主管看的  大概还是能用的,而且这个实在各种examples基础上修改的!

最终发现这个其实如果只这样也不是很难,只要能够得其门而入,后面不会了就可以查资料和api自己搞定了……

总结:只是用grid的话 其实store才是最重要的,grid只是负责显示数据,一般不太会出错,而负责数据这块的store才是出错的重点!

原创粉丝点击