[英]When to compose a Component in the ZK life-cycle?
問題:
在ZK中,使用自定義組件時,生命周期中構建組件內容的最佳時間是什么(任意復雜)。 也就是說,我們什么時候可以安全地假設我們從視圖中獲得了所有數據,但沒有等待太久。
細節:
在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
,例如,通過調用MyCoolComponent
的initializeComponent
函數。
在Composers
的世界里,我們被教導使用doAfterCompose
函數在生命周期的After Compose
階段處理所有這類工作。 對於像這樣創建的Component
是否同樣如此? 如果是這樣,那么最好的(讀取:高效,安全,可讀)方法是什么? 我覺得為onRender
事件附加一個@Listen
是草率的。 有什么想法嗎?
據我所知zk文檔 ,構造函數就像doAfterCompose
,
如果您調用示例中的Selectors
方法。
但你喜歡做什么
public void setTitle(String title) {
this.title = title;
if(label != null)
appendChild(new Label(title));
else
lebel.setValue(title);
}
當進入zul組件<MyComponent>
時,zk生命周期
它調用構造函數,如果有像title="Sean is Cool"
它調用set方法,如果對所有Components
此操作,則會創建頁面。
這對你有幫助嗎?
對於更復雜的結構,有兩種選擇
什么是適合您的目的?
現在生命周期是什么? 對於選項2,只需閱讀文檔。
對於選項1,請在doAfterCompose
或事件偵聽器/處理程序中執行此操作。
好的,這是選項1的示例。
主要的zul
<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);
}});
}
}
您可以在doAfterCompose
調用Executions.CreateComponents
從你的主要zul,但當然,如果你想設置值
在zul中onCreate
方式更好。
要在onCreate()
內部通過java添加組件也可以正常工作,
但如果你把它寫下來,它會更加可修復/可維護。
現在用一句話來問你問題:
最佳時間是將您的Components
初始化為doAfterCompose
並列出Create Event
。
在ZK中,子節點將在其父節點之前創建,您可以在觸發子節點的onCreate事件時設置值,或者在MyCoolDiv的構造函數中添加偵聽onCreate事件的事件偵聽器,然后在該偵聽器中調用init。
有關更多信息,請參閱zk小提琴Div測試中的示例
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.