创建一棵最简单的树需要如下几个环节:
1、创建一个store,并为其实现getChildren方法(获取指定节点的子节点,数据层面)。
2、使用刚刚创建的store创建一个Model,Model只能是ObjectStoreModel(我们用新store嘛)。创建Model的时候一定要指定一个query配置项,该配置项决定了树的根,根必须是唯一。
3、使用Model创建Tree。
4、调用Tree的startup方法, 这一步根据实际情况决定是否需要。
5、happy!!!
如下是一个简单的示例,需要说明的是:
1、模拟数据在当前目录下的treedata.json中,使用dojo/text插件加载。
2、我使用的是chrome所以JSON是内置的全局属性。3、模拟数据为
[{"id":"world","name":"The earth","type":"planet","population":"6 billion"},{"id":"AF","name":"Africa","type":"continent","population":"900 million","area":"30,221,532 sq km","timezone":"-1 UTC to +4 UTC","parent":"world"},{"id":"EG","name":"Egypt","type":"country","parent":"AF"},{"id":"KE","name":"Kenya",{"id":"Nairobi","name":"Nairobi","type":"city","parent":"KE"},{"id":"Mombasa","name":"Mombasa",{"id":"SD","name":"Sudan",{"id":"Khartoum","name":"Khartoum","parent":"SD"},{"id":"AS","name":"Asia",{"id":"CN","name":"China","parent":"AS"},{"id":"IN","name":"India",{"id":"RU","name":"Russia",{"id":"MN","name":"Mongolia",{"id":"OC","name":"Oceania","population":"21 million",{"id":"EU","name":"Europe",{"id":"DE","name":"Germany","parent":"EU"},{"id":"FR","name":"France",{"id":"ES","name":"Spain",{"id":"IT","name":"Italy",{"id":"NA","name":"North America",{"id":"SA","name":"South America","parent":"world","checked":"true"}]
require(["dojo/store/Memory","dijit/Tree","dijit/tree/ObjectStoreModel","dojo/text!./treedata.json"],function(Memory,Tree,ObjectStoreModel,data){ var data = data.replace(/[\n\r\t]/g,""); var treeData = JSON.parse(data); var myStore = new Memory({ // 创建store data : treeData,getChildren: function(object){ // 实现getChildren方法 return this.query({parent: this.getIdentity(object)}); } }); var treeModel = new ObjectStoreModel({ // 使用store创建model store: myStore,query: {id: 'world'} }); var tree = new Tree({ // 创建树 id : "tree",// 树id,可以根据该id使用registry模块的byId方法获取组件对象。 model : treeModel,// dndController: dndSource,// 节点间拖拽需要,还需要其他代码配合,此处并未实现拖拽 showRoot : false,// 是否显示树根 //openOnClick : true,// 单击展开 persist: false,// 持久化到cookie,记住上次打开树时候的状态 // autoExpand : true,// 自动展开所有层次的节点 //openOnDblClick : true // 双击展开 },'treeDiv'); tree.startup(); });
到此简单的树就完成了,其他的功能就需要大家阅读文档了。文档地址为http://dojotoolkit.org/reference-guide/1.8/dijit/Tree.html#dijit-tree顺便还能看看More examples。