justgin.bap.TreePanel = Ext.extend(Ext.tree.TreePanel, { title: '树', rootText: '根节点', rootId: '', manageAble: true, autoScroll: true, url: '/Domain/DynamicTreeAjax.do', //查询数据的地址 urlParams: {}, serviceUrl: '', //外部接口,查询数据的serviceUrl checkBox: false //指定是否有复选框 });
b.然后,扩展initComponent方法,以实现动态加载数据的功能:
initComponent: function() { var me = this this.addEvents( "beforeloadnode", "loadnode" ) //设置根节点 var rootConfig = { text: me.rootText, id: me.rootId, draggable: false, leaf: false } this.root = new Ext.tree.AsyncTreeNode(rootConfig) if(me.url != '') { this.loader = new Ext.tree.TreeLoader({ dataUrl: me.url, params: Ext.apply(me.urlParams, {serviceUrl: me.serviceUrl}), listeners: { 'beforeload': function(l, n) { me.fireEvent('beforeloadnode', n, me) l.baseParams = Ext.apply(me.urlParams, {serviceUrl: me.serviceUrl}) }, 'load': function(l, n) { me.fireEvent('loadnode', n, me) l.baseParams = Ext.apply(me.urlParams, {serviceUrl: me.serviceUrl}) } } }); if(me.checkBox) { Ext.apply(this.loader, {baseAttrs: {uiProvider : Ext.ux.TreeCheckNodeUI}}); } } me.on("render", function(me) { me.getRootNode().expand(false) }), justgin.bap.TreePanel.superclass.initComponent.call(this); }
c.扩展方法getSelected(),返回单选时,当前选中的节点
getSelected: function() { var nd = this.getSelectionModel().getSelectedNode(); return nd; }
d.扩展方法getChecked(),返回有复选框时,选中的节点的集合(TODO)
e.后台返回数据的格式为Ext.tree.Panel可接受的josn格式,如下格式所示,目前许多开源的jsonUtility都提供json格式的封装,后面会专门开篇介绍本人对业务对象与json数据之间转换的设计。
[{ "text": "adapter", "id": "source\/adapter", "cls": "folder" }, { "text": "dd", "id": "source\/dd", "cls": "folder" }, { "text": "debug.js", "id": "source\/debug.js", "leaf": true, "cls": "file" }]
4.使用方法
var tree = new Beidasoft.Bap.TreePanel({ id: 'lefttree', title: 'SampleTreePanel', border: false, serviceUrl: 'ExtObjectData/extTree', //此处请求的是后台Bean中的一个方法,返回能接受的json格式 renderTo: 'divtest' });