JSF + Dynatree to make a tree representation
I'd like to draw a tree that is generated in JSF.
I thought I'd use DynaTree
and avoid using component libraries, although i'm starting to have second thoughts seeing the complexity of the solution.
I thought I could pass a String represen开发者_开发百科tation of the tree using a hidden input to Javascript
and then build the tree there.
Is there a better solution that I had not thought of?
Using JSF2.0
What I eventually did is to generate a JSON string that represents the tree (in dynatree format) and then simply use JSON.Parse() on the other side (browser) to make a tree out of it.
The relevant code is: The Java tree node:
class GroupTreeNode {
public getNodes();
public getGroupId();
public getName();
}
Generate the Tree String:
public String generateTreeString()
{
GroupTreeNode[] root = getGroupTreeBean()
.getGroupsTreeRoot("groupTree");
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < root.length; i++)
{
genSubTree(root[i], sb);
}
sb.append("]");
return sb.toString();
}
private void genSubTree(GroupTreeNode node, StringBuilder sb)
{
// Check if the last character is a '}' in which case we need to add a comma
char[] chararray = new char[1];
sb.getChars(sb.length()-1, sb.length(), chararray, 0);
if (chararray[0] == '}') {
sb.append(", ");
}
// Carry on...
sb.append("{");
// Group Name
sb.append("\"title\":\"");
sb.append(node.getName());
sb.append("\", ");
// Group ID (Custom Node Tab)
sb.append("\"groupID\":\"");
sb.append(node.getGroupId());
sb.append("\"");
// Children (Only if applicable)
if (node.getNodes().length > 0) {
sb.append(", \"isFolder\":true, \"children\":[");
for (int i =0; i < node.getNodes().length; i++)
{
genSubTree(node.getNodes()[i], sb);
}
sb.append("]");
}
sb.append("}");
}
The String is passed through JSF into an <h:inputText id="tree" style="display:none" />
and then the JavaScript
parsing:
function buildTree(sTree) {
var builtobj = JSON.parse(sTree);
return builtobj;
}
var jsfString = $("#tree").val();
console.log("Building a tree with:" + jsfString);
$("#fleet_tab_tree").dynatree({
onActivate : function (node) {
console.log("You activated " + node.data.title + ", with groupID=" + node.data.groupID);
// Do whatever you want with the node values
},
persist : true,
children : buildTree(jsfString),
clickFolderMode: 1
});
I agree with you than dynatree is a robust and a proven component. On the contrary of some JSF native tree components that have less features.
I have start an adapter for dynatree. You could find the source here https://github.com/nithril/dynatree-for-jsf
Comments are welcome!
精彩评论