I was working on some GWT events the other day, events that required me to perform a specific action on an existing View widget, such as refreshing the page currently being displayed or updating a specific piece of data on a page.
In the application I am working on, I’m leveraging the SimpleEventBus to register my EventHandler while the page is active. Once the page went inactive due to being added to a history widget, or was removed from the DOM, I wanted to deregister the EventHandler so that it wasn’t active and responding to fired events unnecessarily. The SimpleEventBus featured an addHandler method that allowed me to register the EventHandler, but it does not have a removeHandler method that allows for the removal of the EventHandler that was registered. So I dug around a bit and realized that the SimpleEventBus.addHandler returns an HandlerRegistration object. An example of what I’m doing can be found in the following code:
/** handlerRegistration. */ protected static HandlerRegistration handlerRegistration = null; @Override public void go(ViewPlaceholder placeholder) { if (handlerRegistration == null) { handlerRegistration = AppContext.getInstance().getEventBus().addHandler( ChangeEvent.TYPE, this); } }
So, after registering the EventHandler, and storing the HandlerRegistration object as a class variable, when I was unloading and removing the View widget I removed the EventHandler by calling the .removeHandler method on the HandlerRegistration and reset the class variable to null. You can see the code I’m using below, that is removing the handler using the stored class variable.
public void remove() { handlerRegistration.removeHandler(); handlerRegistration = null; }
And there you have it. Just remember, you’ve got to keep the HandlerRegistration available if you plan on removing an EventHandler from the EventBus.