花了两天时间来做帮助文档生成树的的任务,期间遇到了许多问题,这里就说几点吧
public class Help extends ActiveRecordBase { @Id private Integer id; @Column private Integer pId; @Column private String name; @Column private Integer sort; // 由于url在easyui-tree里是不存在的属性,所以必须使用它提供的专门用来设 置属性的元素attributes,如下mapa @Column private String url; @Column private String iconCls; @Column private Integer status; //easyui-tree的特有属性,用来设定额外属性的,不需要和数据库关联 private Map<String,Object> attributes = new HashMap<String, Object>(); //判断是否有子节点 public int getChildCount() throws Exception { return (int)count(Help.class, "pId=?", new Object[]{id}); } public String findChildIds() throws Exception { String s = ""; List<Integer> ids = new ArrayList<Integer>(); ids.add(id); while(!ids.isEmpty()){ int id = ids.remove(0); s += id + ","; for(Help help: Help.findAll(Help.class, "pId=?", new Object[]{id})){ ids.add(help.getId()); } } if (!s.equals("")){ s = s.substring(0, s.length() - 1); } return s; } ...... //getter/setter
public View getItems() throws Exception { List<Map<String,Object>> items = new ArrayList<Map<String,Object>>(); List<Help> helps = Help.findAll(Help.class, "pId=0", null, "sort"); for(Help help: helps){ Map<String,Object> item = new HashMap<String,Object>(); item.put("id", help.getId()); item.put("text", help.getName()); //设定attributes,开始时我想在models中装入,而看到同事帮助在此处使用,感觉在此处使用更好 Map<String,Object> attributes = new HashMap<String, Object>(); attributes.put("url", help.getUrl()); item.put("attributes", attributes); items.add(item); } List<Map<String,Object>> doing = new ArrayList<Map<String,Object>>(); doing.addAll(items); while(!doing.isEmpty()){ List<Map<String,Object>> todo = new ArrayList<Map<String,Object>>(); for(Map<String,Object> item: doing){ helps = Help.findAll(Help.class, "pId=?", new Object[]{item.get("id")}, "sort"); if (helps.isEmpty()){ continue; } List<Object> children = new ArrayList<Object>(); for(Help help: helps){ Map<String,Object> child = new HashMap<String,Object>(); child.put("id", help.getId()); child.put("text", help.getName()); Map<String,Object> attributes = new HashMap<String, Object>(); attributes.put("url", help.getUrl()); child.put("attributes", attributes); child.put("state", help.getChildCount() > 0 ? "closed" : "open"); children.add(child); todo.add(child); } item.put("children", children.toArray(new Object[children.size()])); } doing = todo; } System.out.println(new JsonView(items)); return new JsonView(items); }
$(function() { $("#helptree").tree({ line:true, checkbox:false, url:"<c:url value='/doc/help/getItems'/>", onClick: function(node){ if(node.state == null){ var data = $("#helptree").tree('getData',node.target); addTab(node.text,_base+data.attributes.url); } } }); });
上面代码里当触发一个onClick事件时,如何拿到传入的url是一个让人头大的问题,我们试过了onLoadSuccess,以及onClick的好些方法都没有用,后来同事查找更新版本的API发现可以使用getData方法来拿,详见api吧,下面说说几个特性: