Reversing the MVP pattern and using @UiHandler

EDIT: This post has been slightly edited to follow the new naming convention used in Gwt-Platform.

Through usage, we have found that the second MVP pattern proposed by Google could save us a lot of tedious anonymous classes. This approach mainly consists of creating an interface that your presenter implements and which lets your view access some of its methods. This technique can be readily used with Gwt-Platform, but it is lacking documentation. So now is the time to explain it properly!

The first thing you’ll notice is that the latest version of GWTP introduces some interfaces and abstract classes that makes it easy for you to use this pattern:

  • The HasUiHandlers interface is used to indicate that your view participates in the pattern. A view that implements this interface needs to have uiHandlers, that is, a set of methods it can use to initiate complex actions in the presenter.
  • UiHandlers is a marker interface used to define your controls, you inherit from it and define all the methods your view will need to use.
  • The abstract class ViewWithUiHandlers inherits from ViewImpl and is the straightforward implementation of HasUiHandlers. Your view can inherit from it to save you some typing.
  • The abstract class PopupViewWithUiHandlers is the same as the precedent but inherits from PopupViewImpl. Use it for your dialogs that participate in the pattern.

Now don’t be confused by all these tools. You’ll see that using the pattern is quite straightforward. First you need to create an interface that extends UiHandlers and add all the methods your view needs to call. We usually call that interface MyUiHandlers and place it inside the view to keep things organized:

[sourcecode language=”java”]
public interface MyUiHandlers extends UiHandlers {
void onSave();
}
[/sourcecode]

Your presenter then needs to implement this interface:

[sourcecode language=”java”]
public class ExamplePresenter extends Presenter<ExamplePresenter.MyView, ExamplePresenter.MyProxy>
implements MyUiHandlers {

@Override
public void onSave() {
doSomething();
}

}
[/sourcecode]

Then you have to connect these controls to your view. This is done by letting MyView extend HasUiHandlers and by calling setUiHandlers(impl) within your presenter’s constructor to finalize the connection:

[sourcecode language=”java”]
public class ExamplePresenter extends Presenter<ExamplePresenter.MyView, ExamplePresenter.MyProxy> implements MyUiHandlers {
public interface MyView extends View, HasUiHandlers {
}
@Inject
ExamplePresenter(final EventBus eventBus, final MyView view, final MyProxy proxy) {
super(eventBus, view, proxy);
getView().setUiHandlers(this);
}

}
[/sourcecode]

Be careful: since the view is instantiated before the presenter, the setUiHandlers(impl) method will be called after the view’s constructor has executed. This means you cannot refer to the presenter within your view’s constructor. Also, it’s important to call setUiHandlers() early, otherwise you might run into situations where your view needs to access a control when it doesn’t yet have access to them. Just to be on the safe side, you should probably check for null before invoking any control method.

 

The last step is to let your view extends ViewWithUiHandlers or PopupViewWithUiHandlers instead of ViewImpl or PopupViewImpl. Then you’re ready to use your controls via getUiHandlers(). As a result, using the wonderful @UiHandler annotation is now very easy:

[sourcecode language=”java”]
public class ExampleView extends ViewWithUiHandlers<ExampleView.MyUiHandlers> implements MyView {

@UiHandler("saveButton")
void onSaveButtonClicked(ClickEvent event) {
if (getUiHandlers() != null) {
getUiHandlers().onSave();
}
}
[/sourcecode]

That’s it, you now have a powerful, easy to read and versatile way of using your MVP elements without giving more responsibilities to your view and without breaking the MVP pattern. Your presenter still does all the heavy lifting and your view is still pretty dumb so testing should be a breeze!

 

22

Using @ProxyEvent

A relatively recent feature of GWTP is @ProxyEvent, and at first glance it’s not obvious why it should be needed. This post explores how @ProxyEvent works and gives guidelines on when to use it and when to rely on the regular event registration mechanism. First, let’s look at some code that uses this annotation:
[sourcecode language=”java”]
public class MessagePresenter extends Presenter<MessagePresenter.MyView, MessagePresenter.MyProxy> implements ShowMessageHandler {
// …
@ProxyEvent
@Override
public void onShowMessage(ShowMessageEvent event) {
getView().setMessage();
placeManager.revealPlace(new PlaceRequest(NameTokens.messagePage));
}
}
[/sourcecode]
The first thing that’s really important to understand is that, even though @ProxyEvent appears in your presenter, the handler registration occurs within the proxy. In this case, it means that whenever the proxy intercepts a ShowMessageEvent it will instantiate the MessagePresenter and call its onShowMessage. At that point, the presenter is not necessarily visible, so the method reveals it by navigating with placeManager.revealPlace(…). If the presenter is not a place, you could also use forceReveal(). Be carfeul, however, since forceReveal() can lead to undesirable behavior when used on a place.

So when should you use @ProxyEvent? Basically, you use it every time that an event should have the ability to “wake up” your presenter. That is, whenever the presenter should be notified of an event even before it is first instantiated. This is why the method marked with a @ProxyEvent will often contain a mechanism to reveal the presenter.

These types of event handlers dramatically simplify the process of passing a large amount of information to a presenter before revealing it: bundle the information in the event, fire it, intercept it with a @ProxyEvent, and reveal the presenter inside the handler method.

Ok enough theory, let’s expand the previous example. The following code uses an event we already discussed in Gwt-Platform event best practices. The goal, now, is to navigate to MessagePresenter whenever the event is raised.

[sourcecode language=”java”]
public class MessagePresenter extends
Presenter<MessagePresenter.MyView, MessagePresenter.MyProxy> implements ShowMessageHandler {
@ProxyCodeSplit
@NameToken(NameTokens.messagePage)
public interface MyProxy extends ProxyPlace<HomePresenter> {}

public interface MyView extends View {
void setMessage(String message);
}

final private PlaceManager placeManager;

@Inject
MessagePresenter(EventBus eventBus, MyView view, MyProxy proxy, PlaceManager placeManager) {
super(eventBus, view, proxy);
this.placeManager = placeManager;
}

@ProxyEvent
@Override
public void onShowMessage(ShowMessageEvent event) {
getView().setMessage();

placeManager.revealPlace(new PlaceRequest(NameTokens.messagePage));
}

@Override
protected void revealInParent() {
RevealContentEvent.fire(this, AppPresenter.TYPE_SetMainContent, this);
}
}
[/sourcecode]
Now every time a MessageEvent is fired, MessagePresenter will be shown. This works even though @ProxyCodeSplit loads this presenter asynchronously, and without having to couple presenters. The example below shows how PuzzleBazar uses a similar strategy to reveal its LinkColumnPresenter whenever it is needed:
[sourcecode language=”java”]
public class LinkColumnPresenter extends Presenter<LinkColumnPresenter.MyView, LinkColumnPresenter.MyProxy>
implements RevealDefaultLinkColumnHandler {

public interface MyView extends View {}

@ProxyStandard
public interface MyProxy extends Proxy<LinkColumnPresenter> {}

@Inject
public LinkColumnPresenter(
final EventBus eventBus,
final MyView view,
final MyProxy proxy ) {
super(eventBus, view, proxy);
}

@Override
protected void revealInParent() {
RevealContentEvent.fire(this, SplitMainPresenter.TYPE_RevealSideBarContent, this);
}

@ProxyEvent
@Override
public void onRevealDefaultLinkColumn(RevealDefaultLinkColumnEvent event) {
forceReveal();
}
}
[/sourcecode]

Ok, so now that you know how to use @ProxyEvent you may wonder why you shouldn’t always use it! The truth is that, in most cases, there is not much harm in using it to listen to an event. Sometimes, however, it may instantiate a bunch of presenters too early, momentarily slowing down your application. For example, imagine the following:

[sourcecode language=”java”]
// Bad example don’t do this!
@ProxyEvent
@Override
public void onNavigation(NavigationEvent event) {
if (event.getRequest().getNameToken().equals("logout")) {
getView().setMessage( "Logout in process…" );
}
}
[/sourcecode]

At first this may seem reasonable. However, it means your presenter will be instantiated as soon as a NavigationEvent is fired, even if this event has nothing to do with the “logout” place. If you have many such presenters, they will all be instantiated at once! In such cases, you probably want the presenter to register towards the handler in its onBind method:

[sourcecode language=”java”]
// The right way
@Override
protected void onBind(NavigationEvent event) {
super.onBind();
addRegisteredHandler(NavigationEvent.getType(), this);
}
@Override
public void onNavigation(NavigationEvent navigationEvent) {
getView().setMessage( "Logout in process…" );
}
[/sourcecode]

Another drawback of abusing @ProxyEvent is that it makes your proxy code bigger, and since all proxies need to be instantiated when your applications starts, this may increase the initial loading time. As a result the rule of thumb is to use @ProxyEvent whenever you need your presenter to “wake up” to an event, and to use addRegisteredHandler in your onBind() method for all other cases.

I hope this helps you better understand that neat little feature of GWTP. If you need more information, you can always look at Gwt-Platform’s wiki. See you soon!

3

Gwt-Platform event best practices

A newer version of this blog post is available here.

As we worked through enhancing the way events were handled in Gwt-Platform, we came across one constatation, no common pattern was used or encouraged. This post addresses this issue and offers a little tutorial about how to create custom events in Gwt-Platform.

First of all, an event contains two major parts: the Event class itself and an Handler. Those two parts can either sit in different files or be included in the same file, with the Handler nested inside the Event. The second approach is our favorite since Handler is an interface related to an event. Also, it can be done in a few lines and reduce the total number of files.

Give that, here’s how we write our events:

[sourcecode language=”java”]
public class ShowMessageEvent extends
GwtEvent<ShowMessageEvent.ShowMessageHandler> {
public interface ShowMessageHandler extends EventHandler {
void onShowMessage(ShowMessageEvent event);
}

private static Type<ShowMessageHandler> TYPE = new Type<ShowMessageHandler>();

public static void fire(HasEventBus source, String message) {
if (TYPE != null) {
source.fireEvent(new ShowMessageEvent(message));
}
}

public static Type<ShowMessageHandler> getType() {
return TYPE;
}

private final String message;

public ShowMessageEvent(final String message) {
this.message = message;
}

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

public String getMessage() {
return message;
}

@Override
protected void dispatch(ShowMessageHandler handler) {
handler.onShowMessage(this);
}
}[/sourcecode]

Note here the static fire method. This is a convenient static factory method that let’s you fire an event without having to manually instantiate a ShowMessageEvent class. Using these methods is recommended rather than calling directly fireEvent. Also, the first parameter of this method is not the event bus itself, but rather the source. Passing in your presenter as the first parameter will make sure that the event is attached to the real source that triggered it. Using HasEventBus rather than GWT’s HasHandlers increases the type safety of GWTP, ensuring you never fire into a widget an event that was supposed to go on the bus.

Now that we have all the scaffolding for the event, it’s time to figure out how to use it. In Gwt-Platform every presenter implements HasEventBus so they all have the ability to fire events. The best practice approach is to simply use the static fire method of your event. In the above example this would be ShowMessageEvent.fire(this, “Hello world!”);. Some situations will require you to fire events from an object that doesn’t have access to fireEvent(). In this case, the best practice is to inject the EventBus, implement HasEventBus, and relay the call to fireEvent:

[sourcecode language=”java”]
public abstract class MyCustomCallback<T> implements AsyncCallback<T>, HasEventBus {
@Inject
private static EventBus eventBus;

@Override
public void onFailure(Throwable caught) {
ShowMessageEvent.fire(this, "Oops! Something went wrong!");
}

@Override
public void fireEvent(GwtEvent<?> event) {
eventBus.fireEvent(this, event);
}
}
[/sourcecode]

In this case we have used static injection to provide the EventBus (don’t forget to requestStaticInjection in your Gin module!). This is because AsyncCallback classes do not typically participate in dependency injection. If your class does participate in dependency injection then you should use constructor injection. The goal of this pattern is to ensure that event sources are correctly tracked. Since the callback implements HasEventBus it will set itself as the source of the event. More importantly, every class that extends this abstract class will be able to fire any event and set itself as the source.

Now, how do we listen to events travelling on the bus? If you’re listening from a presenter, the prefered way is to use addRegisteredHandler(eventType, eventHandler);. This method not only registers a handler on the event bus, it also makes sure that every registered handler is correctly unregistered when the presenter is unbound. If you are not within a presenter, inject the EventBus and call eventBus.addHandler(eventType, eventHandler);. It is customary to use an anonymous inner class as an eventHandler, for example:

[sourcecode language=”java”]
public abstract class MyPresenter extends PresenterImpl<MyPresenter.MyView, MyPresenter.MyProxy> {

@Override
public void onBind() {
super.onBind();
addRegisteredHandler( ShowMessageEvent.getType(), new ShowMessageHandler() {
@Override
void onShowMessage(ShowMessageEvent event) {
getView().displayMessage( event.getMessage() );
}
} );
}
}
[/sourcecode]

But you can also use the following pattern:

[sourcecode language=”java”]
public abstract class MyPresenter extends PresenterImpl<MyPresenter.MyView, MyPresenter.MyProxy>
implements ShowMessageHandler {

@Override
public void onBind() {
super.onBind();
addRegisteredHandler( ShowMessageEvent.getType(), this );
}

@Override
void onShowMessage(ShowMessageEvent event) {
getView().displayMessage( event.getMessage() );
}
}
[/sourcecode]

I hope this post will help you design your own events, but in any case feel free to leave comments or ask questions! In a future article we will discuss how you can automatically generate most of the boilerplate using GWTP’s annotation processing classes contributed by Brendan Doherty. We will also discuss the use of the @ProxyEvent annotation and how it differs from the events described above.

13

ArcBees birth

ArcBees provides consulting and development services to businesses looking to offer quality web applications to their clients.

Our mission is to be the top developers for cloud-based applications, to be active members of the open source community, to deliver quality web apps that goes way beyond the standard fare and to do that using the best practices of our industry. Our goal is to make sure your clients enjoy the best possible web-based experience, and to make it easy for your application to scale with the growing demand.

We will soon open source the development of our own web site. This blog will guide you through every step we take, letting you catch a glimpse of the subtle decisions and technical tricks needed when building a rich web portal.

There’s a lot of features and news coming up in the near future. Stay tuned, we’ll keep you informed !