[英]How to listen to events across multiple components?
我有一個使用 Spring Boot 和 Vaadin 的項目。 在這個項目中,我有一個包含一些對話框組件的 MainView,在關閉這些對話框后,我希望 MainView 在頁面上顯示一個小加號按鈕,然后單擊此按鈕將重新打開對話框(將來)。 為此,我創建了一個自定義組件事件,將此事件的偵聽器添加到主視圖組件,並在關閉對話框后“觸發”該事件。 問題是 MainView 組件將偵聽器注冊到它自己的事件總線,但是當事件被觸發時(從對話框組件)沒有偵聽器。 這是我的代碼:
public class ComponentCloseEvent extends ComponentEvent<CustomDialog> {
public ComponentCloseEvent(CustomDialog source, boolean fromClient) {
super(source, fromClient);
}
}
// constructor for MainView
public MainView() {
addListener(ComponentCloseEvent.class, e -> System.out.println("I listened to the event!"));
add(new CustomDialog());
}
// method inside CustomDialog
private ButtonEx createCloseButton() {
return new Button("Close", e -> {
fireEvent(new ComponentCloseEvent(this, true));
close();
});
}
當我調試代碼時,不會調用fireEvent
,因為 function hasListeners
返回false
:
protected void fireEvent(ComponentEvent<?> componentEvent) {
if (hasListener(componentEvent.getClass())) {
getEventBus().fireEvent(componentEvent);
}
}
您可以使用 UI 事件總線。 MainView
可以在onAttach()
方法中將偵聽器附加到 UI,組件可以使用ComponentUtil.fireEvent()
實用程序觸發事件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.