仿照官网例子:XmlTreeLoader做的,下面有实例
注意:html文件的库引用请自行解决
- /**
- * 通过读取JSON串生成树的层次结构,务必保证json数组中结点出现次序与树完全展开时一致!
- * (通过后台对编码进行排序来完成)
- * JSON串根节点默认为'list'
- * 父结点id字段为
- *
- * 注意:
- * 1.因为是一次加载全部结点,节点数过多的话将严重影响性能,此时请使用异步加载!
- * 2.结点的id属性对应json中code属性,结点text属性对应json中name属性。
- * 3.根节点的直接子节点的parentcode字段为null或者空字符串都可以
- *
- * v1.1改动:
- * 1.不再需要leaf属性!一个结点是否为叶子结点将基于json中下一个结点是否为其子节点来判断!
- * 本特性将提高转变叶子节点为父节点的操作效率,此时你在界面上给一个叶子结点添加一个子节点
- * 不用再修改叶子结点在后台的leaf属性,你要做的只是保证返回json中的编码规范以及出现次序。
- * 2.如果你设置了leaf属性则此属性将被忽略
- *
- * @author chemzqm@gmail.com
- *
- */
- Ext.ns('Ext.ux.tree');
- Ext.ux.tree.JsonTreeLoader = Ext.extend(Ext.tree.TreeLoader, {
- root: 'list',
- paramName: {
- parentcode: 'parentcode',
- id: 'code'
- },
- // private override
- processResponse: function(response, node, callback){
- var json = response.responseText;
- var array = Ext.decode(json)[this.root];
- try {
- node.beginUpdate();
- node.appendChild(this.parseArray(array));
- node.endUpdate();
- if (typeof callback == "function") {
- callback(this, node);
- }
- }
- catch (e) {
- this.handleFailure(response);
- }
- },
- // private
- parseArray: function(array){
- var pnodes = [];
- var nodes = [];
- for (var i = 0; i < array.length; i++) {
- var o = array[i];//判断是否叶子结点
- if(array[i+1]&&array[i+1][this.paramName.parentcode]==o[this.paramName.id]){
- o.leaf = false;
- }else{
- o.leaf = true;
- }
- var treeNode = this.createNode(o);
- if (!o[this.paramName.parentcode]) {
- nodes.push(treeNode);
- }
- else {
- for (var j = pnodes.length - 1; j >= 0; j--) {
- if (pnodes[j].id == o[this.paramName.parentcode]) {
- pnodes[j].appendChild(treeNode);
- break;
- }
- }
- }
- if (!treeNode.leaf) {
- pnodes.push(treeNode);
- }
- }
- return nodes;
- },
- // private override node的id是json里面的code字段
- createNode: function(o){
- var attr = {
- id: o.code,
- text: o.name
- };
- Ext.applyIf(attr, o);
- attr.loaded = true;
- this.processAttributes(attr);
- return Ext.ux.tree.JsonTreeLoader.superclass.createNode.call(this, attr);
- },
- /*
- * Template method intended to be overridden by subclasses that need to provide
- * custom attribute processing prior to the creation of each TreeNode. This method
- * will be passed a config object containing existing TreeNode attribute name/value
- * pairs which can be modified as needed directly (no need to return the object).
- */
- processAttributes: Ext.emptyFn
- });
- //backwards compat
- Ext.ux.JsonTreeLoader = Ext.ux.tree.JsonTreeLoader;