【问题标题】:How to listen to events across multiple components?如何跨多个组件监听事件?
【发布时间】:2022-11-23 06:24:36
【问题描述】:

我有一个使用 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 没有被调用,因为函数 hasListeners 返回 false

protected void fireEvent(ComponentEvent<?> componentEvent) {
  if (hasListener(componentEvent.getClass())) {
    getEventBus().fireEvent(componentEvent);
  }
}

【问题讨论】:

    标签: java events vaadin


    【解决方案1】:

    您可以使用 UI 事件总线。 MainView 可以在 onAttach() 方法中将监听器附加到 UI,组件可以使用 ComponentUtil.fireEvent() 实用程序触发事件。

    看看这个例子https://cookbook.vaadin.com/ui-eventbus

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-23
      • 2022-07-30
      • 2015-05-07
      • 2017-02-21
      • 1970-01-01
      相关资源
      最近更新 更多