我有一个可扩展的树(在 HTML 页面中):
+ Category 1
- Category 2
+ Subcategory 1
- Subcategory 2
|- Foo
|- Bar
|- Link 42
它由一个结构表示(在后端定义):
class Demo {
static ImmutableList<Item> sample() {
return ImmutableList.of(
new Item("Category 1", ImmutableList.of(
new Item("Some link title", "resource_id_1"),
new Item("Another link title", "resource_id_2"))),
new Item("Category 2", ImmutableList.of(
new Item("Subategory 1", ImmutableList.of(
new Item("Another link title", "resource_id_3"))),
new Item("Subcategory 2", ImmutableList.of(
new Item("Foo", "resource_id_1"),
new Item("Bar", "resource_id_2"),
new Item("Link 42", "resource_id_42"))))));
}
}
定义Item
如下:
public class Item {
private String readableName;
private String resourceId;
private ImmutableList<Item> children;
Item(String name, String resourceId) {
this.readableName = name;
this.resourceId = resourceId;
}
Item(String name, ImmutableList<Item> children) {
this.readableName = name;
this.children = children;
}
public String getReadableName() {
return readableName;
}
public String getResourceId() {
return resourceId;
}
public ImmutableList<Item> getChildren() {
return children;
}
}
resourceId
可以有不同的可读名称,并且可以在整个结构中多次放置,但在当前类别/子类别中只能放置一次。
当前,当用户单击链接或写入 URL 时,资源会被加载(例如链接Foo映射到/showResource?id=resource_id_1:uniqe_magic_id
)并展开树。它之所以起作用,只是因为 hack - 前端创建自己的结构副本,将一些:uniqe_magic_id
字符串附加到每个资源 id(每个叶子),并且在向后端发送请求时,它会删除魔术部分。:uniqe_magic_id
仅由前端用于扩展上面显示的树中的适当项目。这对我来说似乎是一个巧妙的解决方案(我正在重构这段代码并删除cleanId
了我认为没有必要但在向后端发送请求之前剥离魔法的方法......),我正在寻找一个更好的解决方案。
我可以修改前端和后端。我想到了某种带有节点的树,例如:
class Node {
Node next;
Node child;
String readableName;
String resourceId;
String someUniqueHash;
}
并使用someUniqueHash
.
有没有更好的方法来实现相同的结果而不在前端复制整个结构?