2012-05-30 35 views
2

有沒有什麼辦法可以在bean的中心點註冊組件的事件監聽器?如何在JSF中爲bean中的組件註冊事件偵聽器?

是這樣的可能嗎?

@PostConstruct 
public void setup() { 
    FacesContext facesContext = FacesContext.getCurrentInstance(); 
    UIViewRoot view = facesContext.getViewRoot(); 
    view.getComponentByName("toolBar:save").addActionListener(com.sample.SaveListener); 
    view.getComponentByName("form:save").addActionListener(com.sample.SaveListener); 
} 

回答

2

並不是所有的組件在bean的(後期)構建過程中都是必需的。當EL需要首次解析#{bean}時,該bean將被構建,這可能爲時過早。而是在預渲染視圖事件期間執行此操作。

以下標記添加到您的視圖:

<f:event type="preRenderView" listener="#{bean.setup}" /> 

然後你就可以在該方法中做了必要的工作:

public void setup() { 
    UIViewRoot view = FacesContext.getCurrentInstance().getViewRoot(); 
    ((UICommand) view.findComponent("toolBar:save")).addActionListener(new com.sample.SaveListener()); 
    ((UICommand) view.findComponent("form:save")).addActionListener(new com.sample.SaveListener()); 
} 
+0

哇,非常感謝!你只是讓我的一天:)有沒有辦法以這種方式添加非動作監聽器組件? – Budenzauber

+0

您也可以使用'Application#subscribeToEvent()''SystemEventListener'或'ComponentSystemEventListener'實現。 – BalusC

+0

再次感謝,我會仔細看看這兩個:) – Budenzauber

相關問題