TreeCombo

/*
* Sample json load code :
* Ext.getCmp('<combotree>').loadTree(url,params)
* url : '../..../....Action.do?islem=giris '
* params : {'itemId':Ext.getCmp('item').getValue()}
*
 * Animal's TreeCombo modified by Wedgie to handle a maxHeight config setting.
 * This updated version fixes the following problems:
 *   1) Accounts for horizontal scrollbar when calculating required height
 *   2) Set height using correct method to fire resize and update the shadow
 *   3) Realigns the tree with the trigger field when the tree size changes
 */
Ext.ux.TreeCombo = function(config){
    this.addEvents("treeshow", "afterCreateTree","filterNode","blur","afterNodesChecked");
 Ext.ux.TreeCombo.superclass.constructor.call(this, config);
};
Ext.extend(Ext.ux.TreeCombo, Ext.form.TriggerField,
{
    triggerClass: 'x-form-tree-trigger',
    checkModel: null,
    initComponent: function () {
        this.editable = false;
        Ext.ux.TreeCombo.superclass.initComponent.call(this);
        this.on('specialkey', function (f, e) {
            if (e.getKey() == e.ENTER) {
                this.onTriggerClick();
            }
        }, this);
        this.getTree();
    },
    onRender: function (ct, position) {
        if (this.hiddenName && !Ext.isDefined(this.submitValue)) {
            this.submitValue = false;
        }
        Ext.ux.TreeCombo.superclass.onRender.call(this, ct, position);
        this.el.setStyle("overflow", "hidden");
        if (this.hiddenName) {
            this.hiddenField = this.el.insertSibling({
                tag: 'input', type: 'hidden',
                name: this.hiddenName,
                id: (this.hiddenId || this.hiddenName)
            }, 'before', true);
        }
    },
    afterRender: function (ct, position) {
        Ext.ux.TreeCombo.superclass.afterRender.call(this);
        this.el.setStyle("overflow", "hidden");
    },


    onTriggerClick: function () {
        if (this.treePanel.isVisible()) {
            this.treePanel.hide();
        }
        else {
            this.treePanel.show();
            this.treePanel.getEl().alignTo(this.wrap, 'tl-bl?');
        }

    },
    getTree: function () {
        if (!this.treePanel) {
            if (!this.treeWidth) {
                this.treeWidth = Math.max(200, this.width || 200);
            }
            if (!this.treeHeight) {
                this.treeHeight = 200;
            }

            var uiProvider;
            if (this.checkModel != null) {
                uiProvider = Ext.ux.TreeCheckNodeUI;
                this.root.uiProvider = uiProvider;
            }

            this.treePanel = new Ext.tree.TreePanel({
                renderTo: Ext.getBody(),
                loader: this.loader || new Ext.tree.TreeLoader({
                    preloadChildren: (typeof this.root == 'undefined'),
                    url: this.dataUrl || this.url,
                    requestMethod: 'POST',
                    jsonData: true
                }),
                root: this.root || new Ext.tree.AsyncTreeNode({
                    text: '全部',
                    uiProvider: uiProvider
                }),
                rootVisible: (typeof this.rootVisible != 'undefined') ? this.rootVisible : (this.root ? true : false),
                floating: true,
                autoScroll: true,
                minWidth: 200,
                minHeight: 200,
                this.treeWidth,
                height: this.treeHeight,
                listeners:
    {
        hide: this.onTreeHide,
        show: this.onTreeShow,
        click: this.onTreeNodeClick,
        expandnode: this.onExpandOrCollapseNode,
        collapsenode: this.onExpandOrCollapseNode,
        resize: this.onTreeResize,
        scope: this
    }
            });

            if (uiProvider != null) {
                this.treePanel.loader.baseAttrs =
       {
           uiProvider: uiProvider
       };
                this.treePanel.checkModel = this.checkModel;
                var me = this;
                var _selectTo = function () {
                    var ns = me.treePanel.getChecked();
                    var str = idstr = '';
                    for (var i = 0; i < ns.length; i++) {
                        var isNeed = me.fireEvent('filterNode', this, ns[i]);
                        if (!isNeed) {
                            continue;
                        }
                        str = (str==""?"": str+',')+ns[i].text;
                     
                        if (idstr == '') {
                            idstr = ns[i].id;
                        }
                        else {
                            idstr += ',' + ns[i].id;
                        }
                    }
                    me.setRawValue(str);
                    me.setValue(idstr);
                    me.fireEvent('afterNodesChecked',this,idstr);
                }

                var selectTo = function (n) {
                    window.clearTimeout(selectTo.handler);
                    selectTo.handler = setTimeout(_selectTo, 300);
                }

                this.treePanel.on('check', selectTo);
            }
            this.treePanel.show();
            this.fireEvent('afterCreateTree', this, this.treePanel);
            this.treePanel.hide();
            this.relayEvents(this.treePanel.loader, ['beforeload', 'load', 'loadexception']);
            if (this.resizable) {
                this.resizer = new Ext.Resizable(this.treePanel.getEl(),
    {
        pinned: true,
        handles: 'se'
    });
                this.mon(this.resizer, 'resize', function (r, w, h) {
                    this.treePanel.setSize(w, h);
                }, this);
            }
        }
        return this.treePanel;
    },

    onExpandOrCollapseNode: function () {
        if (!this.maxHeight || this.resizable)
            return;
        // -----------------------------> RETURN
        var treeEl = this.treePanel.getTreeEl();
        var heightPadding = treeEl.getHeight() - treeEl.dom.clientHeight;
        var ulEl = treeEl.child('ul');
        // Get the underlying tree element
        var heightRequired = ulEl.getHeight() + heightPadding;
        if (heightRequired > this.maxHeight)
            heightRequired = this.maxHeight;
        this.treePanel.setHeight(heightRequired);
    },

    onTreeResize: function () {
        if (this.treePanel)
            this.treePanel.getEl().alignTo(this.wrap, 'tl-bl?');
    },

    onTreeShow: function () {
        Ext.getDoc().on('mousewheel', this.collapseIf, this);
        Ext.getDoc().on('mousedown', this.collapseIf, this);
        this.fireEvent('treeshow', this);
    },

    onTreeHide: function () {
        Ext.getDoc().un('mousewheel', this.collapseIf, this);
        Ext.getDoc().un('mousedown', this.collapseIf, this);
    },

    onDestroy: function () {
        if (this.treePanel) {
            Ext.destroy(this.treePanel);
        }
        Ext.destroyMembers(this, 'hiddenField');
        Ext.ux.TreeCombo.superclass.onDestroy.call(this);
    },

    collapseIf: function (e) {
        if (!e.within(this.wrap) && !e.within(this.treePanel.getEl())) {
            this.collapse();
        }
    },

    collapse: function () {
        this.treePanel.hide();
        if (this.resizer)
            this.resizer.resizeTo(this.treeWidth, this.treeHeight);
    },

    // private
    validateBlur: function () {
        return !this.treePanel || !this.treePanel.isVisible();
    },

    setValue: function (v) {
        this.startValue = this.value = v;
        //this.el.setStyle("overflow", "hidden");
        if (this.hiddenField) {
            this.hiddenField.value = Ext.value(v, '');
        }
        if (this.checkModel) {
            return;
        }
        if (this.treePanel) {
            var n = this.treePanel.getNodeById(v);
            if (n) {
                this.setRawValue(n.text);
                n.ensureVisible();
                n.select();
            }
            else {
                this.setRawValue(v);
                this.treePanel.expandById(v, true);
            }
        }
    },

    getValue: function () {
        return this.value;
    },

    clearValue: function () {
        if (this.hiddenField) {
            this.hiddenField.value = '';
        }
        this.setRawValue('');
        this.applyEmptyText();
        this.value = '';
        if (this.checkModel) {
            var tp = this.treePanel;
            tp.getRootNode().getUI().checkbox.checked = false;
            return;
        }
    },

    onTreeNodeClick: function (node, e) {
        if (this.checkModel) {
            this.fireEvent('select', this, node);
            return;
        }
        this.selNode = node;
        this.setRawValue(node.text);
        if (this.hiddenField) {
            this.hiddenField.value = Ext.value(node.id, '');
        }
        this.value = node.id;
        this.el.setStyle("overflow", "hidden");
        this.fireEvent('select', this, node);
        this.collapse();
    },

    getSelectNode: function () {
        return this.selNode;
    },
    loadTree: function (url, pr) {
        var tp = this.treePanel;
        tp.getRootNode().removeAll();
        var conn = new Ext.data.Connection();
        conn.request({
            url: url || this.url,
            params: pr || {},
            success: function (a) {
                var tb_items = Ext.util.JSON.decode(a.responseText);
                tp.getRootNode().appendChild(tb_items);
            }
        });
    },

    /*
    * 隐藏指定的节点
    */
    hideNode: function (id) {
        if (this.treePanel.lastHideNode && this.treePanel.lastHideNode.id == id) {
            return;
        }
        if (id && id != "") {
            if (this.treePanel.lastHideNode) {
                var n = this.treePanel.lastHideNode;
                n.hidden = false;
                var realNode = this.treePanel.getNodeById(n.id);
                if (realNode) {
                    realNode.ui.show();
                }
            }
            var node = this.treePanel.getNodeData(id);
            if (node) {
                this.treePanel.lastHideNode = node;
                node.hidden = true;
                if (node.ui) {
                    node.ui.hide();
                }
            }
        }
    }
});
Ext.reg('treecombo', Ext.ux.TreeCombo);

Ext.override(Ext.tree.TreePanel, {
    getNodeData:function (id,path) {
     var tp = this;
     var node = tp.getNodeById(id);
     if(node){
      return node;
     }
     else{
      function child(parent){
       var cs;
       if(parent.children){
        cs = parent.children;
       }
       else if(parent.attributes.children){
        cs = parent.attributes.children;
       }
       if(cs){
        for(var i = 0; i < cs.length; i ++ ){
         if(cs[i].id == id){
          return cs[i];
         }
         var cld = child(cs[i]);
         if(cld)
          return cld;
        }
       }
      };
      
      for(var n in tp.nodeHash){
       var c = child(tp.nodeHash[n]);
       if(c){
        return c;
       }
      }
      
     }
    },
   
    expandById:function (id,select) {
     var tp = this;
        var path="";
  function child(parent,nodePath){
   var cs;
   if(parent.children){
    cs = parent.children;
   }
   else if(parent.attributes.children){
    cs = parent.attributes.children;
   }
   if(cs){
    for(var i = 0; i < cs.length; i ++ ){
     if(cs[i].id == id){
      return nodePath+"/"+parent.id;
     }
     var cld = child(cs[i],nodePath+"/"+parent.id);
     if(cld)
      return cld;
    }
   }
  };
  this.expandPath("/" + this.root.id, null, function(success, node){
   if(success && node){
                var firstNodes=node.childNodes;
          for(var i=0;i<firstNodes.length;i++){
              if (firstNodes[i].id==id) {
                  return true;
              }
           var p = child(firstNodes[i],"/"+node.id);
           if(p){
               tp.expandPath(p,null,function (bSuccess,oLastNode) {
                   var currNode= tp.getNodeById(id);
                   if (bSuccess&&select && currNode) {
                       currNode.ensureVisible();
                       currNode.select();
                   }
               });
            return true;
           }
          }
   }
  });

     
    }

}); 

原文地址:https://www.cnblogs.com/yellowsail/p/1893426.html