dojo树组件现在有两个分支,第一个分支是使用旧store,遵循dojo的data API(该API已经不建议使用,存在于dojo/data文件夹中,但是没办法有的组件还真得用),另一个分支是使用新store,遵循
创建一棵最简单的树需要如下几个环节:
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","type":"country","parent":"AF"},{"id":"Nairobi","name":"Nairobi","type":"city","parent":"KE"},{"id":"Mombasa","name":"Mombasa","type":"city","parent":"KE"},{"id":"SD","name":"Sudan","type":"country","parent":"AF"},{"id":"Khartoum","name":"Khartoum","type":"city","parent":"SD"},{"id":"AS","name":"Asia","type":"continent","parent":"world"},{"id":"CN","name":"China","type":"country","parent":"AS"},{"id":"IN","name":"India","type":"country","parent":"AS"},{"id":"RU","name":"Russia","type":"country","parent":"AS"},{"id":"MN","name":"Mongolia","type":"country","parent":"AS"},{"id":"OC","name":"Oceania","type":"continent","population":"21 million","parent":"world"},{"id":"EU","name":"Europe","type":"continent","parent":"world"},{"id":"DE","name":"Germany","type":"country","parent":"EU"},{"id":"FR","name":"France","type":"country","parent":"EU"},{"id":"ES","name":"Spain","type":"country","parent":"EU"},{"id":"IT","name":"Italy","type":"country","parent":"EU"},{"id":"NA","name":"North America","type":"continent","parent":"world"},{"id":"SA","name":"South America","type":"continent","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。