当前位置 : 主页 > 网页制作 > Dojo >

dojo中Tree的使用

来源:互联网 收集:自由互联 发布时间:2021-06-15
我用的dojo是1.9版本的,所以使用新的store。 创建一棵最简单的树需要如下几个环节: 1、创建一个store,并为其实现getChildren方法(获取指定节点的子节点,数据层面)。 2、使用创建的

我用的dojo是1.9版本的,所以使用新的store。

创建一棵最简单的树需要如下几个环节:
1、创建一个store,并为其实现getChildren方法(获取指定节点的子节点,数据层面)。
2、使用创建的store创建一个Model,Model只能是ObjectStoreModel。创建Model的时候一定要指定一个query配置项,该配置项决定了树的根,根必须是唯一。
3、使用Model创建Tree。
4、调用Tree的startup方法, 这一步根据实际情况决定是否需要。


对应代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<title>测试用例</title>
	<style type="text/css">
		@import "dojo/dojo/resources/dojo.css";
		@import "dojo/dijit/themes/tundra/tundra.css";
		*{margin:0;padding:0;font-family:微软雅黑;font-size:10pt;}
		.earth{border-right:4px solid #DFDFDF; border-bottom:4px solid #DFDFDF; height:100%;width:200px;}
	</style>
	
	<script type="text/javascript" djConfig=" isDebug: false" src="dojo/dojo/dojo.js"></script>
</head>
<script type="text/javascript"> 
	require(["dijit/Tree","dojo/store/Memory","dijit/tree/ObjectStoreModel","dojo/dom","dojo/domReady!"],function(Tree,Memory,ObjectStoreModel,dom)
	{
		var treeData= [
			{"id":"world","name":"地球","type":"planet","population":"6 billion"},
			{"id":"AS","name":"亚洲","type":"continent","parent":"world"},
			{"id":"OZ","name":"欧洲","type":"continent","parent":"world"},
			{"id":"NA","name":"北美","type":"continent","parent":"world"},
			{"id":"SA","name":"南美","type":"continent","parent":"world","checked":"true"},
			{"id":"HG","name":"韩国","type":"country","parent":"AS"},
			{"id":"JP","name":"日本","type":"country","parent":"AS"},
			{"id":"CN","name":"中国","type":"country","parent":"AS"},
			{"id":"YD","name":"印度","type":"country","parent":"AS"},
			{"id":"JND","name":"俄罗斯","type":"country","parent":"AS"},
			{"id":"HK","name":"香港","type":"city","parent":"CN"},
			{"id":"BJ","name":"北京","type":"city","parent":"CN"},
			{"id":"FR","name":"广州","type":"city","parent":"CN"},
			{"id":"HN","name":"湖南","type":"city","parent":"CN"},
			{"id":"CS","name":"长沙","type":"tour","parent":"HN"},
			{"id":"YY","name":"岳阳","type":"tour","parent":"HN"}
		];  
		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,   
			showRoot : true, // 是否显示树根  
			openOnClick : true, // 单击展开  
			persist: true,  // 持久化到cookie,记住上次打开树时候的状态  
			autoExpand : false, // 自动展开所有层次的节点  
			openOnDblClick : true // 双击展开  
		}, "countryData");  
		
  		 tree.startup();  
	});
	
</script>
<body class="tundra">
	<div class="earth">
		<div id="countryData" ></div>
	</div>	
</body>
</html>

本地文件目录显示:有点小bug,但是功能及泵实现了。最好利用Ajax,点击每一层目录的时候才去查询对应子目录,类似于城市级联。本程序没有使用。(dojo放在WebContent目录下)。

indexAction用于跳转index.jsp。

DirFile为领域模型层

package com.xuzengqiang.tree.domain;

public class DirFile
{
	private String fileName; //文件名称,name:fileName
	private String filepath; //文件路径, id:filePath
	private String parentFileName; //父文件路径: parent:parentFileName

	public String getFileName()
	{
		return fileName;
	}

	public void setFileName(String fileName)
	{
		this.fileName = fileName;
	}

	public String getParentFileName()
	{
		return parentFileName;
	}

	public void setParentFileName(String parentFileName)
	{
		this.parentFileName = parentFileName;
	}

	public String getFilepath()
	{
		return filepath;
	}

	public void setFilepath(String filepath)
	{
		this.filepath = filepath;
	}

}
LoadAllFiles,用于读取某个文件下的所有文件。

package com.xuzengqiang.tree.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.xuzengqiang.tree.domain.DirFile;

public class LoadAllFiles
{
	//获取某个盘下面的所有目录
	public static List<DirFile> getAllFiles(String dir)
	{
		List<DirFile> dirFile=new ArrayList<DirFile>();
		File parentFile=new File(dir);
		initFile(parentFile , dirFile );
		return dirFile;
	}
	
	public static void initFile(File parentFile, List<DirFile> dirFile)
	{
		
		File[] subFiles=parentFile.listFiles();
		
		if(subFiles!=null)
		{
			for (File subFile : subFiles)
			{
				DirFile file=new DirFile(); 
				file.setFilepath(subFile.getAbsolutePath());
				file.setFileName(subFile.getName());
				file.setParentFileName(parentFile.getAbsolutePath());
				
				dirFile.add(file);
				
				if(subFile.isDirectory())
				{
					initFile(subFile,dirFile);
				}
			}
		}
	}
	
}
DirFileAction:用于Ajax

package com.xuzengqiang.tree.struts.action;

import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;
import com.xuzengqiang.tree.domain.DirFile;
import com.xuzengqiang.tree.utils.LoadAllFiles;

@SuppressWarnings("serial")
public class DirFileAction extends ActionSupport
{
	private String pathName;

	public String getPathName()
	{
		return pathName;
	}

	public void setPathName(String pathName)
	{
		this.pathName = pathName;
	}

	@Override
	public String execute() throws Exception
	{
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=UTF-8");
		response.setHeader("Parma", "0");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expiress", 0);
		PrintWriter out = response.getWriter();
		
		List<DirFile> dirFile = LoadAllFiles.getAllFiles(pathName);
		
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < dirFile.size(); i++)
		{
			buffer.append("[");
			buffer.append(dirFile.get(i).getFilepath());
			buffer.append(",");
			buffer.append(dirFile.get(i).getFileName());
			buffer.append(",");
			buffer.append(dirFile.get(i).getParentFileName());
			buffer.append("]");
		}
		String dirFiles = buffer.toString();

		out.print(dirFiles);
		out.flush();
		out.close();
		return null;
	}

}

index.jsp页面。主要是dojoAjax的实现,利用dojo.request,

参数:第一个、必需的参数是请求的URL。第二个参数是一个包含请求选项的对象(非必需)。常用的选项有下面几个:

method--代表HTTP方法的大写字符串。dojo提供了几个帮助函数来更方便的指定这个选项(request.get,request.post,request.put,request.del)。

sync--布尔值。true:同步请求方式,请求阻塞知道服务区返回响应或者超时;fasle:异步请求方式。

query--附加在URL后面的查询参数,可以是一个字符串或者键值对。

data--字符串或者键值对,或者FormData对象,它们包含要发送给服务器的数据。

handleAs--代表如何转化服务器响应中负载(或者叫响应数据)的字符串。经过转化的服务器响应数据才会传递给回调函数。可能的格式是“text"(默认值),"json","javascript"和”xml"。

headers--包含请求头的键值对。

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
<head>
	<title>测试用例</title>
	<style type="text/css">
		@import "dojo/dojo/resources/dojo.css";
		@import "dojo/dijit/themes/tundra/tundra.css";
		*{margin:0;padding:0;font-family:微软雅黑;font-size:10pt;}
		.earth{border-right:4px solid #DFDFDF; border-bottom:4px solid #DFDFDF;width:900px;}
	</style>
	
	<script type="text/javascript" djConfig=" isDebug: false" src="dojo/dojo/dojo.js"></script>
</head>
<script type="text/javascript"> 
	require([
	         "dijit/Tree",
	         "dojo/store/Memory",
	         "dijit/tree/ObjectStoreModel",
	         "dojo/request",
	         "dojo/domReady!"
	        ],function(Tree,Memory,ObjectStoreModel,request)
	{
		var pathName="D:\\Maven"; //同样做为根路径
	  	request.post("${pageContext.request.contextPath}/dirFileAction", 
		{
	        data: 
	        {
	        	pathName:pathName
	        },
	        handleAs:"text"
	    }).then(function(text)
	    {
	    	var treeData= [
					{"id":pathName,"name":pathName}
				];  
			var myStore = new Memory(
				{ 
					data : treeData,  
					getChildren: function(object)
					{
						return this.query({parent: this.getIdentity(object)});  
					}   
				});  
       		
			var dirFiles=text.split("]");
			for(var i=0;i<dirFiles.length-1;i++)
			{
				var dirFile=dirFiles[i].split(",");
				var filePath=dirFile[0].substr(1); //文件的绝对路径作为id
				var fileName=dirFile[1];           //文件名作为显示
				var parentFileName=dirFile[2];     //父文件名,同样为绝对路径
				myStore.add({"id":filePath,"name":fileName,"parent":parentFileName});
			}
			
       		var treeModel = new ObjectStoreModel(
       		{ 
    			store: myStore,  
    			query: {id:pathName}  
    		});  
    		var tree = new Tree(
    		{ 
    			id : "tree", 
    			model : treeModel,   
    			showRoot : true, 
    			openOnClick : true,   
    			persist: true, 
    			autoExpand : false, 
    			openOnDblClick : true
    		}, "fileTree");  
    		
      		 tree.startup();  
	    });
	});
	
</script>
<body class="tundra">
	<div class="earth">
		<div id="fileTree" ></div>
	</div>	
</body>
</html>
结果视图:

网友评论