问题:
在 ZK 中,当使用自定义组件时,生命周期中构建组件内容(任意复杂)的最佳时间是什么时候。也就是说,我们什么时候可以安全地假设我们拥有来自 View 的所有数据,而无需等待太久。
详情:
在 ZK 中,我可以创建一个自定义组件 MyCoolComponent
:
package my.package;
public class MyCoolComponent extends Div {
private String title;
public MyCoolComponent() {
Selectors.wireVariables(this, this, Div.class);
Selectors.wireComponents(this, this, false);
Selectors.wireEventListeners(this, this);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
// When is the correct time to call this function?
public void initializeComponent() {
appendChild(new Label(title));
// arbitrarily complex initialization follows ..
}
}
我可以像这样在 zul 文件中使用我的自定义组件:
<?component name="coolcomponent" class="my.package.MyCoolComponent" ?>
<zk>
<coolcomponent id="cool" height="200px" title="Sean is Cool" />
</zk>
现在,当使用这个 Component
时,我想添加子 Components
,例如,通过调用 中的
.initializeComponent
函数MyCoolComponent
在 Composers
的世界里,我们被教导在生命周期的 After Compose
阶段处理所有此类工作,并使用 doAfterCompose
功能。这样创建的 Component
也是这样吗?如果是这样,最好的(阅读:高效、安全、可读)方法是什么?我觉得为 onRender
事件附加一个 @Listen
是草率的。有什么想法吗?
最佳答案
据我了解zk docs ,构造函数类似于 doAfterCompose
,
如果你调用Selectors
示例中的方法。
但你喜欢做的可能是
public void setTitle(String title) {
this.title = title;
if(label != null)
appendChild(new Label(title));
else
lebel.setValue(title);
}
zk生命周期是,当进入一个zul组件时<MyComponent>
如果有类似 title="Sean is Cool"
的东西,它会调用构造函数
它调用 set 方法,如果对所有 Components
都这样做它创建页面。
这对您有帮助吗?
编辑
对于更复杂的结构,有两种选择
- 用你需要的结构创建一个 zul 文件并使用 Executions#CreateComponent或
- 创建您自己的 zk-Component-Widget包
哪种方法最适合您的目的?
- 如果您有一个要(重新)使用的 zk 组件结构,请选择 1。
论坛帖子的结构可能就是这样。 - 选择2.如果你想
添加特殊功能,
优化/定制客户端-服务器通信,
为 JavaScript 库编写绑定(bind),
在客户端保持较小的内存大小, (即使对于复杂的结构你只需要一个类)
... .
自己的组件肯定有很多好处,
但实现它们需要时间。
现在生命周期是什么?对于选项 2,只需阅读文档即可。
对于选项 1,请在 doAfterCompose
中进行或者在事件监听器/处理程序中。
好的,这是选项 1 的示例。
主要祖尔
<zk>
...
<div id="menu" use="myPkg.MyMenu" item1="omg" />
...
</zk>
我的菜单定义
<vbox>
<label id="item1" value="${arg.item1}">
...
</vbox>
Java
class MyMenu extends Div {
String item1;
...
public void setItem1(String x){
item1 = x;
}
// onCreate is fired before data is send to the client,
// but after the Component and all it children exists.
public void onCreate(CreateEvent ev){
Executions.CreateComponents("MenuDef.zul", this, new HashMap<String, Object>(){{
put("item1", item1);
}});
}
}
您可以调用 Executions.CreateComponents
在doAfterCompose
也来自你的主要 zul,但当然如果你想设置值
在祖尔 onCreate
方法更好。
在 onCreate()
中通过 java 添加组件工作也很好,
但如果您将内容写在 zul 中,它会更易于编辑/维护。
现在用一句话回答你的问题:
最好的时间是初始化你的 Components
在doAfterCompose
并通过列出到 Create Event
.
关于java - 何时在 ZK 生命周期中组合组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14361185/