There is a potential for memory leaks via event listeners due to
cyclical references between DOM and JS. To avoid this, GWT manages the
event listeners via the Widget lifecycle. When the widget is attached
to the DOM (i.e. it or it's ancestor is attached to a RootPanel) the
widget's event listener is initialized. When the widget is detached
(or the page is unloaded) the event listener is cleaned up. You can
see the code in Widget.onAttach() and Widget.onDetach().
I'd say it is erroneous to use Widget outside of the normal Widget
containment hierarchy. Instead, we can set an event listener directly:
DOM.setEventListener(buttonElement, new EventListener()
{
// you will only get the events you sink
void onBrowserEvent(Event event)
{
// references in this method can result in a memory leak
Window.alert("GWT-hacky-clicked!");
}
});
// connect the foreign element to the GWT event dispatcher
DOM.sinkEvents(buttonElement, Event.ONCLICK);
Also consider adding a Window CloseHandler to prevent the memory leak.
Window.addCloseHandler(new CloseHandler<Window>() {
public void onClose(CloseEvent<Window> event)
{
DOM.setEventListener(buttonElement, null);
}
});
You can also look at HandlerManager and DomEvent.fireNativeEvent() to
see how to translate Event into a ClickEvent, but IMO that is
overkill.
-= Mat