下面將介紹如何異步取一棵樹的所有節點,具體做法與官方同步取節點有很大不同,尤其在json的id屬性上,下面是我一些摸索,可能不是最佳方案,有待大家一起研究。
異步取節點的思路是這樣的:
1、先定義一個初始化節點(也可以不定義,看個人需求)
2、yui-ext根據該節點id請求服務器,獲得子節點各屬性
3、循環
特點:可以在上一級目錄中,在服務器端預先將該節點是否有子節點讀好(json中的isLeaf屬性),雖然但數據庫將多承擔一些壓力,但用個count(*)不會造成太大負擔(除非查詢條件異常復雜),也可以不讀,即把所有isLeaf設置為false。
問題:
1、目前還無法進行reload,即每次打開節點都重新讀取一次
2、樣式還有些問題,無法通過node. childNodes[i]設置子節點的style,所以無法改變最后一級元素的style(也許是通過別的途徑改變style的?)
示例:
先給出一段js代碼,可以結合官方的demo(http://yui-ext.com/playpen/yui-ext.0.40/examples/tree/reorder.html)看看:
//定義根id的變量 var rootId = 1; var TreeTest = function(){ // shorthand var Tree = YAHOO.ext.tree; return { init : function(userName){ var tree = new Tree.TreePanel('detailTree', { animate:true, //這個dataUrl是初始化樹所用的url,你也可以不寫或定義一個靜態json文件,還可以什么都不寫全部依賴于第二個url自動產生,視具體需求而定 loader: new Tree.TreeLoader({dataUrl:'calendarDetail.do?method=getDayDetailJSON&parentId='+rootId}), enableDD:true, containerScroll: true }); // set the root node var root = new Tree.AsyncTreeNode({ text: 'yui-ext', draggable:false, id:rootId }); tree.setRootNode(root); //根據當前節點id,動態拼出請求服務器的路徑 //每產生一個節點,指向一個事件的引用,將新建loader.dataUrl(具體事件的機制還需要再研究) //注意調用函數是beforeload tree.on('beforeload', function(node){ tree.loader.dataUrl = 'calendarDetail.do?method=getDayDetailJSON&parentId='+node.id; }); //這里演示一個自定義json的用法(description為自定義json的key) //以及如何定義某節點的style(node.ui.textNode.style.title) //具體可以看ui這個類 tree.on('beforeexpand', function(node){ node.ui.textNode.style.title = ‘red’; alert(node.attributes.description); }); // render the tree tree.render(); // false for not recursive (the default), false to disable animation root.expand(); } }; }();
同時再分析一個json:
[{"text":"衣服類",
"id":"5", //注意:這里是該節點的id,拼連接時要用到,與官方的json有所不同
"leaf":true,
"cls":"file",
"description":"這里是衣服類"}] //自定義只需要這樣就可以了
給出java產生json的代碼邏輯片斷:
…… //list為由傳入的id所求的category集合 Listlist= findBy("parentId", new Long(parentId.toString())); StringBuffer JSONStr = new StringBuffer(); //聲明json JSONStr.append("["); for(CostCategory i : list){ boolean isLeaf = isLeaf(i.getId()); //isLeaf()為判斷是否有以該id為parentId的節點,具體沒有給出 String icon = isLeaf?"file":"folder"; String description = i.getCategoryDescription()==null?"":i.getCategoryDescription(); //{"text":"treedata.jsp","id":"treedata.jsp","leaf":true,"cls":"file"}, JSONStr.append("{\"text\":\""+ i.getCategoryName()+"\",\"id\":\""+ i.getId()+"\",\"leaf\":"+ isLeaf+",\"cls\":\""+ icon+"\",\"description\":\""+ description+"\"},"); } JSONStr.deleteCharAt(JSONStr.lastIndexOf(",")); JSONStr.append("]"); System.out.println(JSONStr); out.print(JSONStr); //輸出json …… 本文轉自:http://www.ajaxjs.com/yuicn/article.asp?id=20070241
---------------------------------------------------------------------------------------------------------------------------------
說人之短,乃護己之短。夸己之長,乃忌人之長。皆由存心不厚,識量太狹耳。能去此弊,可以進德,可以遠怨。
http://www.aygfsteel.com/szhswl
------------------------------------------------------------------------------------------------------ ----------------- ---------