Documentation for @UiHandler

Roalt picture Roalt · Aug 9, 2010 · Viewed 16.7k times · Source

I started to look into using GWT in combination with UiBuilder. I'm a bit puzzled about how you can use the @UiHandler(..) directive to make simple event handle code as written down in the GWT documentation:

@UiHandler("button")
void handleClick(ClickEvent e) {
  Window.alert("Hello, AJAX");
}

In this case the method handleClick is used. How do you know for each GWT widget what methods can be created with @UiHandler? For some you can also create a doClose() method.

But what can you use with, for instance, a ListBox to get an event an item is selected? Where in the documentation can I see this?

Answer

Igor Klimer picture Igor Klimer · Aug 9, 2010

The parameter you pass to the @UiHandler annotation is the name of the appropriate field you want to assign that *Handler. So, in this case you are assigning a ClickHandler to a Button button (actually, we just know the field's name).

As for how this exactly works - it's part of GWT magic :) My guess is that, just like any other UiBinder related code (I think there was a presentation on Google IO, that showed the code that UiBinder generates), at compilation time the compiler figures out what goes where. In this example: we have a Button button, and we have a @UiHandler annotated method that has a ClickEvent parameter -> that must mean it's a ClickHandler (notice that the method's name doesn't matter). So let's add some code at compile time (in the constructor, probably) that adds that handler to the button. If you are interested in a more comprehensive answer - check out the source :D

But what can you use with, for instance, a ListBox to get an event an item is selected? Where in the documentation can I see this?

In the GWT API reference. In this case, you are probably looking for ListBox.addChangeHandler. But you usually won't find @UiHandler related code there - that's because it would be redundant - you always construct the @UiHandler methods the same way:

  1. You check the *Handler that you want to add, say ChangeHandler
  2. It has a void onChange(ChangeEvent event) - so, your method needs a ChangeEvent parameter and should look like this:

    @UiHandler("listBox")
    void whateverName(ChangeEvent event) {
        // ...
    }