码迷,mamicode.com
首页 > Web开发 > 详细

ExtJs4之TreePanel

时间:2014-08-14 16:31:58      阅读:327      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   java   使用   os   

Tree介绍

树形结构,是程序开发,不可缺少的组件之一。ExtJs中的树,功能强大美观实用。功能齐全,拖拉,排序,异步加载等等。

在ExtJs4中Tree和Grid具有相同的父类,因此Grid具有的特性和插件在Tree上也能用。

1.ExtJs4之Grid详细

2.ExtJs4之TreePanel

简单的Tree 

bubuko.com,布布扣 

代码:

bubuko.com,布布扣
<head>
    <title></title>
     <link href="/ExtUI/ExtJs4.2.1/resources/css/ext-all.css" rel="stylesheet" type="text/css" />
    <link href="/ExtUI/mecss/UIicon.css" rel="stylesheet" type="text/css" />
    <script src="/ExtUI/ExtJs4.2.1/ext-all.js" type="text/javascript"></script>
    <script src="/ExtUI/ExtJs4.2.1/locale/ext-lang-zh_CN.js" type="text/javascript"></script>
    <script type="text/javascript">

        Ext.onReady(function () {
            //型录树Store
            var treeStore = Ext.create(Ext.data.TreeStore, {
                proxy: {
                    type: ajax,
                    url: /Tools/106.ashx?method=getCatalogItem&cataId= + 886
                },
                fields: [text, id, leaf, cataId]
            });
            //型录树
            var CatalogTtree = Ext.create(Ext.tree.Panel, {
                store: treeStore,
                border: false,  //边框
                renderTo: Ext.getBody(),
                enableDD: true,
                rootVisible: false,  //隐藏根节点
                useArrows:true, //树节点使用箭头
                containerScroll: true,
                collapsible: false,
                autoScroll: false,                
                //singleExpand:true   //展示单个子节点,其它的子节点合并。
            });         
           CatalogTtree.expandAll(); //展开所有节点
           //CatalogTtree.collapseAll(); //关闭所有节点
           
            
               
         });

    </script>
</head>
View Code

treePanel展开所有,关闭所有

 CatalogTtree.expandAll(); //展开所有节点
 CatalogTtree.collapseAll(); //关闭所有节点

TreeGrid简例,带弹出window的form表单

bubuko.com,布布扣bubuko.com,布布扣

代码:

bubuko.com,布布扣
 Ext.onReady(function () {

            //获取store
            var ClassTreeGridStore = Ext.create(‘Ext.data.TreeStore‘, {
                model: ‘Task‘,
                proxy: {
                    type: ‘ajax‘,
                    actionMethods: {
                        create: "POST", read: "POST", update: "POST", destroy: "POST"
                    },
                    url: ‘/queClass/GetClassTreeStore‘
                },
                fields: ["qcId", "claName", "pId", "lowScroe", "topScore"],
                folderSort: true
            });

            //获取tbar
            var tbar = Ext.create("Ext.toolbar.Toolbar", {
                items: [
                    {
                        text: ‘添加兄弟分类‘,
                        iconCls: ‘a_add‘,
                        handler: function () {
                            AddDialog.setTitle("添加兄弟分类");
                            AddForm.form.reset();
                            Ext.getCmp("btnAdd").show();
                            Ext.getCmp("btnEdit").hide();
                            Ext.getCmp("pName").hide();
                            Ext.getCmp("bName").show();
                            if (typeof (ClassTreeGrid) == "undefined") {
                                return false;
                            }
                            var rows = ClassTreeGrid.getView().getSelectionModel().getSelection();
                            if (typeof (rows[0]) == "undefined") {
                                Ext.Msg.alert("提示", "请选择要操作的行!");
                                return false;
                            }
                            Ext.getCmp("bName").setValue(rows[0].data.claName);
                            AddDialog.show();
                        }
                    }, ‘-‘,
                     {
                         text: ‘添加子分类‘,
                         iconCls: ‘a_add‘,
                         handler: function () {
                             AddDialog.setTitle("添加子分类");
                             AddForm.form.reset();
                             Ext.getCmp("btnAdd").show();
                             Ext.getCmp("btnEdit").hide();
                             Ext.getCmp("bName").hide();
                             Ext.getCmp("pName").show();
                             if (typeof (ClassTreeGrid) == "undefined") {
                                 return false;
                             }
                             var rows = ClassTreeGrid.getView().getSelectionModel().getSelection();
                             if (typeof (rows[0]) == "undefined") {
                                 Ext.Msg.alert("提示", "请选择要操作的行!");
                                 return false;
                             }
                             Ext.getCmp("pName").setValue(rows[0].data.claName);
                             AddDialog.show();
                         }
                     }, ‘-‘,
                    {
                        text: ‘删除‘,
                        iconCls: ‘a_cross‘,
                        handler: DelClass
                    }, ‘-‘,
                    {
                        text: ‘修改‘,
                        iconCls: ‘a_edit‘,
                        handler: function () {
                            AddDialog.setTitle("修改分类");
                            AddForm.form.reset();
                            Ext.getCmp("btnEdit").show();
                            Ext.getCmp("btnAdd").hide();
                            Ext.getCmp("bName").hide();
                            Ext.getCmp("pName").hide();
                            if (typeof (ClassTreeGrid) == "undefined") {
                                return false;
                            }
                            var rows = ClassTreeGrid.getView().getSelectionModel().getSelection();
                            if (typeof (rows[0]) == "undefined") {
                                Ext.Msg.alert("提示", "请选择要操作的行!");
                                return false;
                            }
                            AddForm.form.setValues(rows[0].data);
                            AddDialog.show();
                        }
                    }, ‘-‘,
                    {
                        text: "刷新",
                        iconCls: "a_refresh",
                        handler: function () {
                            //刷新treepanel
                            ClassTreeGridStore.load();
                        }
                    }, ‘-‘,
                    {
                        text: ‘展开所有‘,
                        iconCls: ‘a_edit2‘,
                        handler: function () {
                            //展开所有函数
                            ClassTreeGrid.expandAll();
                        }
                    }, ‘-‘,
                    {
                        text: ‘折叠所有‘,
                        iconCls: ‘a_lock‘,
                        handler: function () {
                            //折叠所有函数
                            ClassTreeGrid.collapseAll();
                        }
                    }
                ]
            });

            //treegrid
            var ClassTreeGrid = Ext.create(‘Ext.tree.Panel‘, {
                tbar: tbar,
                useArrows: true,
                rootVisible: false,
                store: ClassTreeGridStore,
                multiSelect: false,
                singleExpand: false,
                columns: [{   //定义tree的列
                    xtype: ‘treecolumn‘,
                    text: ‘分类名称‘,  //显示的表头列名称
                    flex: 2,
                    sortable: true,
                    dataIndex: ‘claName‘  //对应store的列字段名称
                }, {
                    text: ‘最小分值‘,
                    flex: 1,
                    dataIndex: ‘lowScroe‘,
                    sortable: true
                }, {
                    text: ‘最大分值‘,
                    flex: 1,
                    dataIndex: ‘topScore‘,
                    sortable: true
                }]
                , listeners: {
                    //点击行触发事件
                    itemclick: function (record, node) {
                        //把列的qcid传递给QuesGridStore刷新对应的grid或tree
                        QuesGridStore.load({ params: { csId: node.data.qcId } });
                    }
                }
            });          


            //弹出window的form表单
            var AddForm = Ext.create("Ext.form.Panel", {
                border: false,
                fieldDefaults: {
                    msgTarget: ‘side‘,  //提示信息在右旁边显示图标
                    labelWidth: 105,
                    align: "right",
                    regexText: ‘格式错误‘, //错误提示
                    allowBlank: false //不与许为空
                },
                defaults: {
                    padding: 15,
                    width: 380
                },
                defaultType: "textfield",
                items: [
                     {
                         xtype: "hidden",
                         name: ‘pId‘,
                     },
                     {
                         fieldLabel: ‘父分类名称‘,
                         id: "pName",
                         name: ‘pName‘,
                         disabled: true
                     },
                      {
                          fieldLabel: ‘兄弟分类名称‘,
                          id: "bName",
                          name: ‘bName‘,
                          disabled: true
                      },
                     {
                         fieldLabel: ‘分类名称‘,
                         name: ‘claName‘,

                     },
                    {
                        //表单中的数字控件
                        xtype: "numberfield",
                        fieldLabel: ‘最小分值‘,
                        name: ‘lowScroe‘,
                        regex: /^\d+$/,  //正则验证
                        maxLength: 100,
                    },
                    {   //表单中的数字控件
                        xtype: "numberfield",
                        fieldLabel: ‘最大分值‘,
                        regex: /^\d+$/,
                        regexText: ‘格式错误‘,
                        name: ‘topScore‘,
                    }
                ]
            });

            //要弹出的window
            var AddDialog = Ext.create("Ext.window.Window", {
                iconCls: ‘a_add‘,
                closeAction: ‘hide‘,        //窗口关闭的方式:hide/close
                resizable: false,
                closable: true,            //是否可以关闭
                modal: true,                //是否为模态窗口
                items: AddForm,
                buttons: [{
                    text: ‘添加‘,
                    iconCls: ‘a_add‘,
                    id: "btnAdd",
                    handler: function () {
                        if (AddForm.form.isValid()) {
                            if (AddDialog.title == ‘添加兄弟分类‘) {
                                //O为兄弟分类,1为子分类
                                AddClass(0);
                            }
                            else {
                                AddClass(1);
                            }
                        }
                    }
                },
                {
                    text: ‘修改‘,
                    iconCls: ‘a_edit‘,  //样式
                    id: "btnEdit",
                    handler: EditClass
                },
                {
                    id: "btnCancel",
                    iconCls: ‘a_cross‘,  //样式
                    text: ‘重置‘,
                    handler: function () {
                        //重置AddForm.form表单
                        AddForm.form.reset();
                    }
                }]
            });
            new Ext.Viewport({
                layout: "border",
                renderTo: Ext.getBody(),
                defaults: {
                    bodyStyle: "background-color: #FFFFFF;",
                    frame: true
                },
                items: [{ region: "north", height: "60%", split: true, layout: "fit", border: true, items: [ClassTreeGrid] }
                       
                ]
            });

            //添加分类
            function AddClass(type) {
                var rows = ClassTreeGrid.getView().getSelectionModel().getSelection();
                var id = 0;
                var leaf = false;
                //兄弟分类
                if (type == 0) {
                    id = rows[0].data.pId;
                }
                else {
                    id = rows[0].data.qcId;
                }
                Ext.Ajax.request({
                    method: "post",
                    url: "/queClass/Add",
                    params: { json: Ext.JSON.encode(AddForm.form.getValues()), id: id },
                    callback: function (options, success, response) {
                        if (success) {
                            var json = response.responseText;
                            json = Ext.decode(json);
                            ClassTreeGridStore.load();
                            Ext.Msg.alert("提示", json.msg);
                            AddDialog.hide();
                        }
                        else {
                            Ext.Msg.alert("提示", "系统繁忙");
                        }
                    }
                });
            }
            //删除分类
            function DelClass() {
                var rows = ClassTreeGrid.getView().getSelectionModel().getSelection();
                if (typeof (rows[0]) == "undefined") {
                    Ext.Msg.alert("提示", "请选择要操作的行!");
                    return false;
                }
                Ext.Ajax.request({
                    method: "post",
                    url: "/queClass/Delete/",
                    params: { qcId: rows[0].data.qcId },
                    callback: function (options, success, response) {
                        if (success) {
                            var json = response.responseText;
                            json = Ext.decode(json);
                            ClassTreeGridStore.load();
                            Ext.Msg.alert("提示", json.msg);
                            AddDialog.hide();
                        }
                        else {
                            Ext.Msg.alert("提示", "系统繁忙");
                        }
                    }
                });
            }
            //修改分类
            function EditClass() {
                var rows = ClassTreeGrid.getView().getSelectionModel().getSelection();
                if (typeof (rows[0]) == "undefined") {
                    Ext.Msg.alert("提示", "请选择要操作的行!");
                    return false;
                }
                Ext.Ajax.request({
                    method: "post",
                    url: "/queClass/Edit/",
                    params: { json: Ext.JSON.encode(AddForm.form.getValues()), qcId: rows[0].data.qcId },
                    callback: function (options, success, response) {
                        if (success) {
                            var json = response.responseText;
                            json = Ext.decode(json);
                            ClassTreeGridStore.load();
                            Ext.Msg.alert("提示", json.msg);
                            AddDialog.hide();
                        }
                        else {
                            Ext.Msg.alert("提示", "系统繁忙");
                        }
                    }
                });
            }
        });
View Code

treepanel右键菜单编辑

bubuko.com,布布扣bubuko.com,布布扣 

代码:

bubuko.com,布布扣
   //GUID
        function newGuid() {
            var guid = "";
            for (var i = 1; i <= 32; i++) {
                var n = Math.floor(Math.random() * 16.0).toString(16);
                guid += n;
                if ((i == 8) || (i == 12) || (i == 16) || (i == 20))
                    guid += "-";
            }
            return guid;
        }

        //Toopitp
        Ext.tip.QuickTipManager.init();

        

        //Model
        Ext.define(‘MyTreeModel‘, {
            extend: ‘Ext.data.Model‘,
            fields: [‘text‘,‘id‘,‘leaf‘,‘caitNo‘]
        });  

        //Store
        Ext.define("MyTreeStore", {
            extend: "Ext.data.TreeStore",
            model: ‘MyTreeModel‘,
            proxy: {
                type: ‘ajax‘,
                api: {
                    read: ‘/Tools/106.ashx?method=getCatalogItem‘,
                },
                writer: {
                    type: ‘json‘,
                    allowSingle: false,
                    encode: true,
                    root: ‘records‘
                }
            },
            root: {
                id: -1,
                expanded: true,
                text: cataId,
            },
            autoLoad: true
        });

        var MyTreeStore = Ext.create("MyTreeStore");

        Ext.define("MyTreePanel", {
            extend: ‘Ext.tree.Panel‘,
            width: 250,
            height: 400,
            store: MyTreeStore,
            hideHeaders: true,
            rootVisible: true,
            viewConfig: {
                plugins: {
                    ptype: ‘treeviewdragdrop‘
                },
                listeners: {
                    drop: function (node, data, dropRec, dropPosition) {
                        store.sync();
                    }
                }
            },

            initComponent: function () {
                var me = this;              
                //可编辑
                me.plugins = [me.cellEditingPlugin = Ext.create(‘Ext.grid.plugin.CellEditing‘)];
                //定义列
                me.columns = [{
                    xtype: ‘treecolumn‘,
                    dataIndex: ‘text‘,
                    flex: 1,
                    editor: {
                        xtype: ‘textfield‘,
                        selectOnFocus: true,
                        validator: function (value) {
                            value = Ext.String.trim(value);
                            return value.length < 1 ? this.blankText : true;
                        }
                    }
                }, {
                    xtype: ‘actioncolumn‘,
                    width: 24,
                    icon: ‘/ExtUI/Image/a_delete.gif‘,
                    iconCls: ‘x-hidden‘,
                    tooltip: ‘删除‘,
                    handler: Ext.bind(me.handleDeleteClick, me)
                }];

                //定义菜单
                Ext.define(‘SimpleTasks.view.lists.ContextMenu‘, {
                    extend: ‘Ext.menu.Menu‘,
                    xtype: ‘listsContextMenu‘,
                    items: [
                            {
                                text: ‘兄弟节点‘,
                                iconCls: ‘a_add‘,
                                id: ‘new-list-item‘,
                                handler: me.handleNewListClick,
                                scope: me
                            },
                            {
                                text: ‘孩子节点‘,
                                iconCls: ‘a_add‘,
                                id: ‘new-folder-item‘,
                                handler: me.handleNewFolderClick,
                                scope: me
                            },
                            {
                                text: ‘删除‘,
                                iconCls: ‘a_delete‘,
                                id: ‘delete-folder-item‘,                               
                            },
                            {
                                text: ‘刷新‘,
                                iconCls: ‘a_refresh‘,
                                id: ‘refresh-folder-item‘,
                                handler: function () {
                                    MyTreeStore.load({ params: grid.getView().getSelectionModel().getSelection()[0].data });
                                }
                            }
                        ]

                });

                //定义底部tbar
                me.dockedItems = [{
                    xtype: ‘toolbar‘,
                    dock: ‘bottom‘,
                    items: [{
                        iconCls: ‘a_add‘,
                        tooltip: ‘兄弟节点‘,
                        handler: me.handleNewListClick,
                        scope: me
                    }, {
                        iconCls: ‘a_add‘,
                        tooltip: ‘孩子节点‘,
                        handler: me.handleNewFolderClick,
                        scope: me
                    }, 
                    {
                        iconCls: ‘a_delete‘,
                        id: ‘delete-folder-btn‘,
                        tooltip: ‘删除‘,
                        scope: me
                    },
                    {
                        iconCls: ‘a_refresh‘,
                        id: ‘refesh-folder-btn‘,
                        tooltip: ‘刷新‘,
                        handler: function () {
                            MyTreeStore.load({ params: grid.getView().getSelectionModel().getSelection()[0].data });
                        }
                    }
                    ]
                }];

                me.contextMenu = Ext.create("SimpleTasks.view.lists.ContextMenu");

                me.callParent();               
                me.on("itemmouseenter", me.showActions);
                me.on("itemmouseleave", me.hideActions);
                me.on("edit", me.updateNode);
                me.on("afterrender", me.handleAfterListTreeRender);
                me.on("beforeedit", me.handleBeforeEdit, me);
                me.on("canceledit", me.handleCancelEdit);
                me.on("itemcontextmenu", me.showContextMenu, me);
                
            },

            //刷新树
            refreshView: function () {
                //refresh the data in the view.  
                //This will trigger the column renderers to run, 
                this.getView().refresh();
            },

            //显示actioncolumn
            showActions: function (view, list, node, rowIndex, e) {
                var icons = Ext.DomQuery.select(‘.x-action-col-icon‘, node);
                if (view.getRecord(node).get(‘id‘) != "-1") {
                    Ext.each(icons, function (icon) {
                        Ext.get(icon).removeCls(‘x-hidden‘);
                    });
                }
            },

            //隐藏actioncolumn
            hideActions: function (view, list, node, rowIndex, e) {
                var icons = Ext.DomQuery.select(‘.x-action-col-icon‘, node);
                Ext.each(icons, function (icon) {
                    Ext.get(icon).addCls(‘x-hidden‘);
                });
            },

            //Handles a click on a delete icon
            handleDeleteClick: function (gridView, rowIndex, colIndex, column, e, record) {
               var thisNodes=this;
               Ext.Ajax.request({
                   url:"/Tools/106.ashx?method=deleteTreeNode&cataId="+cataId,
                   params:record.data,
                   callback:function(options,success,response){
                       if(success)
                       {
                         var responseJson=Ext.JSON.decode(response.responseText)[0];
                         if(responseJson.status=="true")
                         {
                            //这个model区别于普通的model
                            //在定义store的时候并没有定义fields或model属性,该model由treeStore自动创建
                            //该model包含树展示所需要的数据结构,具备parentNode,isLeaf,loaded等属性
                            var model = gridView.getRecord(gridView.findTargetByEvent(e));
                            thisNodes.deleteNode(model);
                            Ext.Msg.alert("提示",responseJson.msg);
                         }
                         else
                         {
                            Ext.Msg.alert("提示",responseJson.msg);
                         }
                       }
                       else
                       {
                           Ext.Msg.alert("提示","请重新操作!");
                       }
                   }                                   
               });
               
            },


            //删除节点
            deleteNode: function (nodel) {
                nodel.parentNode.removeChild(nodel);
                //与服务器端同步
                MyTreeStore.sync();
            },

            //更新节点
            updateNode: function (editor,e,node) {
                var me = this;
//                //与服务器端同步
              //  MyTreeStore.sync(); 

               if(e.record.data.id.length>8)
               {
               
                 //插入
                  Ext.Ajax.request({
                  url:"/Tools/106.ashx?method=createTreeNode&cataId="+cataId,
                  params:e.record.data,
                  callback:function(options,success,response){
                      if(success)
                      {
                          var responJson=Ext.JSON.decode(response.responseText)[0];
                          if(responJson.status=="false")
                          {
                            Ext.Msg.alert("提示",responJson.msg);
                          }
                          else
                          {
                              MyTreeStore.load({ params: grid.getView().getSelectionModel().getSelection()[0].data });
                          }                  
                      }
                      else
                      {
                         Ext.Msg.alert("提示","系统繁忙");
                      }
                  }                  
               });
               }
               else
               {                 
                  //更新
                  Ext.Ajax.request({
                  url:"/Tools/106.ashx?method=updateTreeNode&cataId="+cataId,
                  params:e.record.data,
                  callback:function(options,success,response){
                      if(success)
                      {
                          var responJson=Ext.JSON.decode(response.responseText)[0];
                          if(responJson.status=="false")
                          {
                            Ext.Msg.alert("提示",responJson.msg);
                          }                         
                      }
                      else
                      {
                         Ext.Msg.alert("提示","系统繁忙");
                      }
                  }                  
               });
               }
            },


            //树加载完毕后设置默认选中第一个
            handleAfterListTreeRender: function (tree) {
                tree.getSelectionModel().select(0);
            },

            //编辑前判断跟节点不允许编辑
            handleBeforeEdit: function (editingPlugin, e) {
                return e.record.get(‘id‘) !== -1;
            },

            //取消编辑事件
            handleCancelEdit: function (editor, e) {
                var list = e.record,
                        parent = list.parentNode;
                parent.removeChild(list);
                this.getListTree().getSelectionModel().select([parent]);
            },

            //添加叶子节点
            handleNewListClick: function (component, e) {
                this.addNode(true);
            },

            //添加跟节点
            handleNewFolderClick: function (component, e) {
                this.addNode();
            },

            //添加节点
            addNode: function (leaf) {
                var me = this;
                var listTree = me;               
                cellEditingPlugin = listTree.cellEditingPlugin,
                    selectionModel = listTree.getSelectionModel(),
                    selectedList = selectionModel.getSelection()[0],                 

                    parentList = leaf?selectedList.parentNode : selectedList,
                    newList = Ext.create(‘MyTreeModel‘, {
                        id: newGuid(),
                        text: ‘New List‘,
                        leaf: true,
                        loaded: true
                    }),
                    expandAndEdit = function () {
                        if (parentList.isExpanded()) {
                            selectionModel.select(newList);
                            cellEditingPlugin.startEdit(newList, 0);
                        } else {
                            listTree.on(‘afteritemexpand‘, function startEdit(list) {
                                if (list === parentList) {
                                    selectionModel.select(newList);
                                    cellEditingPlugin.startEdit(newList, 0);
                                    // remove the afterexpand event listener
                                    listTree.un(‘afteritemexpand‘, startEdit);
                                }
                            });
                            parentList.expand();
                        }
                    };
                //判断是否是子节点
                if(selectedList.isLeaf())
                {
                    if(!leaf) //判断是添加子节点还是兄弟节点
                    {
                       MyTreeStore.getNodeById(selectedList.data.id).set(‘leaf‘, false);
                    }
                }
                parentList.appendChild(newList);
                if (listTree.getView().isVisible(true)) {
                    expandAndEdit();
                } else {
                    listTree.on(‘expand‘, function onExpand() {
                        expandAndEdit();
                        listTree.un(‘expand‘, onExpand);
                    });
                    listTree.expand();
                }
            },

            //添加右键菜单
            showContextMenu: function (view, list, node, rowIndex, e) {
                this.contextMenu.showAt(e.getX(), e.getY());
                e.preventDefault();
            }
        });
      
        //编辑树Window
        var EditTreeWindow=Ext.create("Ext.window.Window",{
            title: ‘编辑树‘,
            iconCls:‘a_edit‘,              
            closeAction: ‘hide‘,        //窗口关闭的方式:hide/close
            resizable: false,   
            closable: true,            //是否可以关闭
            modal: true,                //是否为模态窗口
            items: Ext.create("MyTreePanel")
        });
View Code

 

1.ExtJs4之Grid详细

2.ExtJs4之TreePanel

这一篇,我都只是视图,然后代码,如果多有疑问,欢迎你加入左上角的群,咱们一起努力,进步。

 

ExtJs4之TreePanel,布布扣,bubuko.com

ExtJs4之TreePanel

标签:des   style   blog   http   color   java   使用   os   

原文地址:http://www.cnblogs.com/knowledgesea/p/3552503.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!