+ 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
方法,我认为这不是必要的,但在向后端发送请求之前会strip掉magic...),我正在寻找更好的解决方案。
我可以修改前端和后端。我考虑过一些节点的树形结构:
class Node {
Node next;
Node child;
String readableName;
String resourceId;
String someUniqueHash;
}
并且使用 someUniqueHash
。
有没有更好的方法在前端实现相同的结果而不必复制整个结构?
new Item(String, ImmutableList<Item>)
构造函数将子项的ID更改为以父项的ID开头怎么样?这样你就会拥有唯一的ID,无需复制或更改结构。 - HericDenis