使用dojo的tree,使用dojotree
dojo的Tree很是靈活,但是官方網站上的例子卻很少,而且也比較分散,後續將持續完善本例子。
總的來說,要使用tree,要接觸到三個類:"dojo/store/JsonRest","dijit/tree/ObjectStoreModel","dijit/Tree"。
通過JsonRest非同步從服務端擷取資料。
ObjectStoreModel可以設定判斷當前資料是否有子結點的方法、資料中哪個屬性用來作為label顯示在樹中,資料使用什麼表徵圖顯示等。
Tree具體顯示樹。
var usGov = new JsonRest({target : "/rest/getTreeData",//擷取樹資料的URLgetChildren : function(object) {//如何擷取下級資料,這裡與官方例子裡的不一樣,官方例子裡要求返回的資料資訊中要同時返回當前結點資料,大多數情況下這個是多餘的,使用下面的程式, 服務端只需要返回下級結點資料的數組即可。if (typeof object.children == "undefined") {//這段程式,判斷到當本結點的資料的下級資料已經有了後,就不需要再從服務端擷取了。return this.query({PID:object.ID}).then(function(fullObject) {return fullObject;});} else {return object.children;}}});// create model to interface Tree to storevar model = new ObjectStoreModel({store : usGov,//query: {PID: "root"},//通常情況下這個是不需要設定的,如果不設定,從服務端擷取根結點資料時將不傳參數mayHaveChildren : function(object) {//判斷資料是否有兒子,當結點展開時是否會調用上面store中的getChildren方法,就是通過這個方法判斷的return !object.leaf;//本處於官方例子不一樣,並不是複用children屬性的,程式更為清析。},getLabel : function(object) {//資料對象中個屬性是用來顯示在樹結點中的。return object.NAME;}});<pre name="code" class="javascript">var tree = new Tree({model : model,persist : false,showRoot : true,region : 'center',//如果父容器是BorderContainer,指定樹顯示在該父容器中間style : "overflow:hide;padding:0px;"});
本樹結點第一次從服務端擷取根結點的資料例子:
<pre name="code" class="javascript">[{NAME: "US Government", id: "a1",ID:"1", leaf:false, children:[{ NAME: "Congress2", id: "a2", ID:"2", leaf:false },{ NAME: "Congress3", id: "a3", ID:"3", leaf:true }]}]
</pre><pre code_snippet_id="500089" snippet_file_name="blog_20141028_20_3872161" name="code" class="javascript">展開樹中Congress2結點時從服務端擷取的資料例子:
<pre name="code" class="javascript">[{ NAME: "Congress4", id: "a4", ID:"4", leaf:false, children:[{ NAME: "Congress6",id: "a6",ID:"6",leaf:true}, {NAME: "Congress7",id: "a7",ID:"7",leaf:true}]}, {NAME: "Congress5",id: "a5",ID:"5",leaf:true}]
特別要注意,資料中的id屬性一定要有,並且不能重複,否則在結點展開的時候可能不會觸發從後台擷取資料的動作。
對於 dojo tree 重新整理的問題
你可以把擷取json資料的方法寫在addOnLoad()裡面,如:
function jsonData(){
//這裡寫你對json資料的操作
}
dojo.addOnLoad(jsonData);
這樣應該可以解決你重新整理的問題
參考資料://
struts2中dojo的tree控制項,怎在載入tree的同時,預設執行頂層node,即parentnode的select/onclick事件?
window.onload=function(){
var nodes =dojo.widget.manager.getWidgetsByType('struts:StrutsTreeNode');
nodes[0].markSelected();
}