Create Async Tree
To create Async Tree, every tree node must has a 'id' attribute which will post to back to retrieve children nodes data.
We will build an example using etmvc framework to return the nodes JSON data.
Create a HTML Markup
<ul id="tt"></ul>
Build jQuery Code
We use the url property for retrieving remote data.
$('#tt').tree({ url:'/demo2/node/getNodes' // The url will be mapped to NodeController class and getNodes method });
Data Model
@Table(name="nodes") public class Node extends ActiveRecordBase{ @Id public Integer id; @Column public Integer parentId; @Column public String name; public boolean hasChildren() throws Exception{ long count = count(Node.class, "parentId=?", new Object[]{id}); return count > 0; } }
Writing Controller Code
If a node has children, remember to set the node state to 'closed'.
public class NodeController extends ApplicationController{ /** * get nodes, if the 'id' parameter equals 0 then load the first level nodes, * otherwise load the children nodes * @param id the parent node id value * @return the tree required node json format * @throws Exception */ public View getNodes(int id) throws Exception{ List<Node> nodes = null; if (id == 0){ // return the first level nodes nodes = Node.findAll(Node.class, "parentId=0 or parentId is null", null); } else { // return the children nodes nodes = Node.findAll(Node.class, "parentId=?", new Object[]{id}); } List<Map<String,Object>> items = new ArrayList<Map<String,Object>>(); for(Node node: nodes){ Map<String,Object> item = new HashMap<String,Object>(); item.put("id", node.id); item.put("text", node.name); // the node has children, // set the state to 'closed' so the node can asynchronous load children nodes if (node.hasChildren()){ item.put("state", "closed"); } items.add(item); } return new JsonView(items); } }
Database Configuration Example
domain_base_class=com.et.ar.ActiveRecordBase com.et.ar.ActiveRecordBase.adapter_class=com.et.ar.adapters.MySqlAdapter com.et.ar.ActiveRecordBase.driver_class=com.mysql.jdbc.Driver com.et.ar.ActiveRecordBase.url=jdbc:mysql://localhost/mydb com.et.ar.ActiveRecordBase.username=root com.et.ar.ActiveRecordBase.password=soft123456 com.et.ar.ActiveRecordBase.pool_size=0
Deploy the example
- Create a MySql database.
- Import the test table data from path '/db/nodes.sql', the table is named 'nodes'.
- Change the database configuration if needed, the configration file is placed in /WEB-INF/classes/activerecord.properties.
- Run the program http://localhost:8080/demo2/
| Download the Async Tree example: easyui-async-tree.zip |
2010-02-01
-----------
苦读有恒 天道酬勤
0 评论:
发表评论