如何使用 GWT EventBus [英] How to use the GWT EventBus

查看:24
本文介绍了如何使用 GWT EventBus的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何使用 EventBus 或者是否有更好的解决方案来通过项目发送 Event.

I wonder how to use the EventBus or whether there are some better solutions to send an Event through the project.

Widget1 有一个 Button.Widget2 有一个 Label,当我按下按钮时它应该会改变.这些小部件位于 DockLayout 中:

Widget1 has a Button. Widget2 has a Label, that should change when I press the button. These widgets are in a DockLayout:

RootLayoutPanel rootLayoutPanel = RootLayoutPanel.get();
DockLayoutPanel dock = new DockLayoutPanel(Unit.EM);

dock.addWest(new Widget1(), 10);
dock.add(new Widget2());

rootLayoutPanel.add(dock);

我在 Widget1 中声明了一个 handleClickAlert:

I have declared an handleClickAlert in Widget1:

@UiHandler("button")
void handleClickAlert(ClickEvent e) {
    //fireEvent(e); 
}

推荐答案

当你将项目划分为逻辑部分时(例如使用 MVP),那么不同的部分有时需要进行沟通.典型的这种通信是通过发送状态变化来完成的,例如:

When you divide the project into logical parts (for example with MVP), then the different parts sometimes need to communicate. Typical this communication is done by sending status changes, e.g.:

  • 用户登录/注销.
  • 用户通过 URL 直接导航到页面,因此需要更新菜单.

在这些情况下使用事件总线是非常合乎逻辑的.

Using the event bus is quite logical in those cases.

要使用它,您需要为每个应用实例化一个 EventBus,然后由所有其他类使用.要实现这一点,请使用静态字段、工厂或依赖项注入(GWT 中的 GIN).

To use it you instantiate one EventBus per app which is then used by all other classes. To achieve this use a static field, factory or dependency injection (GIN in case of GWT).

以您自己的事件类型为例:

Example with your own event types:

public class AppUtils{

    public static EventBus EVENT_BUS = GWT.create(SimpleEventBus.class);
}

通常您还会创建自己的事件类型和处理程序:

Normally you'd also create your own event types and handlers:

public class AuthenticationEvent extends GwtEvent<AuthenticationEventHandler> {

public static Type<AuthenticationEventHandler> TYPE = new Type<AuthenticationEventHandler>();

  @Override
public Type<AuthenticationEventHandler> getAssociatedType() {
    return TYPE;
}

@Override
protected void dispatch(AuthenticationEventHandler handler) {
    handler.onAuthenticationChanged(this);
}
}

和处理程序:

public interface AuthenticationEventHandler extends EventHandler {
    void onAuthenticationChanged(AuthenticationEvent authenticationEvent);
}

然后你像这样使用它:

AppUtils.EVENT_BUS.addHandler(AuthenticationEvent.TYPE, new AuthenticationEventHandler()     {
        @Override
        public void onAuthenticationChanged(AuthenticationEvent authenticationEvent) {
            // authentication changed - do something
        }
    });

并触发事件:

AppUtils.EVENT_BUS.fireEvent(new AuthenticationEvent());

这篇关于如何使用 GWT EventBus的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆