Friday, December 4, 2009

EventBus and gwt

When using gwt and following best practice as recommended by google you will come across the EventBus. The EventBus makes it easy for multiple sources to listen to the same event, it makes your event handling easier. Below I will show you a simple example using the EventBus.

You find the recommended implementtation of the eventbus in the Gwt-Presenter library which is a library for the MVP(Model View Presenter) pattern.

Also I recommend reading the blog post by Chris Lowe where he shows how all the tools work together
http://blog.hivedevelopment.co.uk/2009_08_21_archive.html


First off we need an event.

package org.testapp.client;

import com.google.gwt.event.shared.GwtEvent;

public class MessageEvent extends GwtEvent{
 
 public static Type TYPE = new Type();
 final String message;
 
 public MessageEvent(String msg){
  message = msg;
 }
 
 public String getMessage(){
  return message;
 }
 

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

 @Override
 protected void dispatch(MessageEventHandler handler) {
  handler.onMessage(this);
 }
}



And the interface for the event handlers.
package org.testapp.client;

import com.google.gwt.event.shared.EventHandler;

public interface MessageEventHandler extends EventHandler{

 void onMessage(MessageEvent evt);
}



And when we want to fire an event we create it and add it to the event bus.
eventBus.fireEvent( new MessageEvent( display.getTextWidget().getValue() ));


And finaly we register the event handler
eventBus.addHandler(MessageEvent.TYPE, new MessageEventHandler(){

 @Override
 public void onMessage(MessageEvent evt) {
  // TODO Auto-generated method stub
  display.setMessage( evt.getMessage() );
 }
 
});




No comments:

Post a Comment