When you divide a project into logical parts (for example, using MVP), sometimes you have to communicate with different parts. A typical message sends status changes, for example:
- user logged in / logged out.
- the user moves directly through the URL to the page so that the menu is updated.
In this case, the use of event logic is quite logical.
To use it, you instantiate one EventBus for each application, which is then used by all other classes. To do this, use a static field, factory, or dependency injection (GIN in the case of GWT).
Example with custom event types:
public class AppUtils{ public static EventBus EVENT_BUS = GWT.create(SimpleEventBus.class); }
Usually you 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); } }
and handler:
public interface AuthenticationEventHandler extends EventHandler { void onAuthenticationChanged(AuthenticationEvent authenticationEvent); }
Then you use it as follows:
AppUtils.EVENT_BUS.addHandler(AuthenticationEvent.TYPE, new AuthenticationEventHandler() { @Override public void onAuthenticationChanged(AuthenticationEvent authenticationEvent) {
and fire the event:
AppUtils.EVENT_BUS.fireEvent(new AuthenticationEvent());
Peter Knego May 17 '11 at 11:54 2011-05-17 11:54
source share