tags:

views:

215

answers:

3

How should widgets in GWT inform other widgets to refresh themselfs or perform some other action.

Should I use sinkEvent / onBrowserEvent? And if so is there a way to create custom Events?

+1  A: 

It's a very open ended question - for example, you could create your own static event Handler class which widgets subscribe themselves to. e.g:

Class newMessageHandler {
    void update(Widget caller, Widget subscriber) {
        ...
    }
}

customEventHandler.addEventType("New Message", newMessageHandler);

Widget w;
customEventHandler.subscribe(w, "New Message");

...
Widget caller;

// Fire "New Message" event for all widgets which have
// subscribed
customEventHandler.fireEvent(caller, "New Message");

Where customEventHandler keeps track of all widgets subscribing to each named event, and calls the update method on the named class, which could then call any additional methods you want. You might want to call unsubscribe in the destructor - but you could make it as fancy as you want.

Richard Franks
This might work for what I have in mind, will certainly give it a try.
Drejc
+2  A: 

I have solved this problem using the Observer Pattern and a central Controller. The central controller is the only class that has knowledge of all widgets in the application and determines the way they fit together. If someone changes something on widget A, widget A fires an event. In the eventhandler you call the central controller through the 'notifyObservers()' call, which informes the central controller (and optionally others, but for simplicity I'm not going into that) that a certain action (passing a 'MyEvent' enum instance) has occurred.

This way, application flow logic is contained in a single central class and widgets don't need a spaghetti of references to eachother.

Confusion
You came to the same solution as I did. Trying first the sendNotification, recieveNotification mechanism would get much to complicated. The observer pattern fits perfect and a central controller makes more sense.
Drejc
A: 

So here is my (sample) implementation, first let's create a new event:

import java.util.EventObject;

import com.google.gwt.user.client.ui.Widget;

public class NotificationEvent extends EventObject
{
    public NotificationEvent(String data)
    {
     super(data);
    }
}

Then we create an event handler interface:

import com.google.gwt.user.client.EventListener;

public interface NotificationHandler extends EventListener
{
    void onNotification(NotificationEvent event);
}

If we now have a widget implementing the NotificationHanlder, we can trigger the event by calling:

((NotificationHandler)widget).onNotification(event);
Drejc