簡體   English   中英

什么時候在ZK生命周期中組成一個組件?

[英]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 ,例如,通過調用MyCoolComponentinitializeComponent函數。

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此操作,則會創建頁面。
這對你有幫助嗎?

編輯

對於更復雜的結構,有兩種選擇

  1. 使用您需要的結構創建一個zul文件並使用Executions#CreateComponent
  2. 創建自己的zk-Component-Widget

什么是適合您的目的?

  • 如果您有(重新)使用的zk組件結構,請選擇1.
    論壇帖子的結構可能是這樣的事情。
  • 如果您願意,請選擇2.
    添加特殊功能,
    優化/成本化客戶端 - 服務器通信,
    為JavaScript lib編寫綁定,
    在客戶端保持較小的內存大小(即使對於復雜的結構,您只需要一個類)
    ......
    自己的組件肯定有很多好處,
    但實施它們需要時間。

現在生命周期是什么? 對於選項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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM