Hey I have a problem getting my head around how custom GWT event Handlers work. I have read quite a bit about the topic and it still is some what foggy. I have read threads
Since this question and the answer from Piotr GWT has added support for a slightly different way to create custom events. This event implementation is specific build to be used with the GWT's EventBus in the package com.google.web.bindery.event.shared. An example on how to build a custom event for GWT 2.4:
import com.google.web.bindery.event.shared.Event;
import com.google.web.bindery.event.shared.EventBus;
import com.google.web.bindery.event.shared.HandlerRegistration;
/**
* Here is a custom event. For comparison this is also a MessageReceivedEvent.
* This event extends the Event from the web.bindery package.
*/
public class MessageReceivedEvent extends Event {
/**
* Implemented by methods that handle MessageReceivedEvent events.
*/
public interface Handler {
/**
* Called when an {@link MessageReceivedEvent} event is fired.
* The name of this method is whatever you want it.
*
* @param event an {@link MessageReceivedEvent} instance
*/
void onMessageReceived(MessageReceivedEvent event);
}
private static final Type TYPE =
new Type();
/**
* Register a handler for MessageReceivedEvent events on the eventbus.
*
* @param eventBus the {@link EventBus}
* @param handler an {@link MessageReceivedEvent.Handler} instance
* @return an {@link HandlerRegistration} instance
*/
public static HandlerRegistration register(EventBus eventBus,
MessageReceivedEvent.Handler handler) {
return eventBus.addHandler(TYPE, handler);
}
private final String message;
public MessageReceivedEvent(String message) {
this.message = message;
}
@Override
public Type getAssociatedType() {
return TYPE;
}
public String getMessage() {
return message;
}
@Override
protected void dispatch(Handler handler) {
handler.onMessageReceived(this);
}
}
The event is used as follows:
To register your handler for this event with the eventbus call the static register method on the MessageReceivedEvent class:
MessageReceivedEvent.register(eventbus, new MessageReceivedEvent.Handler() {
public void onMessageReceived(MessageReceivedEvent event) {
//...do something usefull with the message: event.getMessage();
}
});
Now to fire the event on the eventbus call fireEvent with a newly constructed event:
eventBus.fireEvent(new MessageReceivedEvent("my message"));
Another implementation can be found in GWT's own EntityProxyChange event class. That implementation uses a alternative option of the EventBus. It uses the ability to add handlers that are bound to a specific source, via addHandlerToSource and can be triggered via eventBus.fireEventFromSource.
The event implementation given here is also more suitable when working with GWT's Activities.