当您将项目分为逻辑部分(例如,使用MVP)时,有时需要沟通不同的部分。通常,此通信通过发送状态更改来完成,例如:
- 用户登录/注销。
- 用户直接通过URL导航到页面,因此菜单需要更新。
在这些情况下,使用事件总线是很合逻辑的。
要使用它,您需要
EventBus为每个应用实例化一个,然后由所有其他类使用。为此,请使用静态字段,工厂注入或依赖项注入(对于GWT,为GIN)。
您自己的事件类型的示例:
public class AppUtils{ public static EventBus EVENT_BUS = GWT.create(SimpleEventBus.class);}通常,您还将创建自己的事件类型和处理程序:
public class AuthenticationEvent extends GwtEvent<AuthenticationEventHandler> {public static Type<AuthenticationEventHandler> TYPE = new Type<AuthenticationEventHandler>(); @Overridepublic Type<AuthenticationEventHandler> getAssociatedType() { return TYPE;}@Overrideprotected 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());



