How to use the GWT EventBus

I am not familiar with GWT yet and am wondering how to use EventBus, or if there are some better solutions for sending events through a project.

Widget 1 has a button. Widget 2 has a shortcut that should change when I click the button. These widgets are in DockLayout:

RootLayoutPanel rootLayoutPanel = RootLayoutPanel.get(); DockLayoutPanel dock = new DockLayoutPanel(Unit.EM); dock.addWest(new Widget1(), 10); dock.add(new Widget2()); rootLayoutPanel.add(dock); 

I declared handleClickAlert in Widget 1

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

Hope someone can help me. Thank!

+47
java event-handling events gwt
May 17 '11 at 11:38
source share
1 answer

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) { // authentication changed - do something } }); 

and fire the event:

 AppUtils.EVENT_BUS.fireEvent(new AuthenticationEvent()); 
+104
May 17 '11 at 11:54
source share



All Articles