GWT EventHandler Removal

GWT EventHandler Removal

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;

    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 = 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.

Author: daharveyjr

I’m a solution architect responsible for the design, development, implementation, testing, and maintenance of e-commerce operations and applications using the Hybris and WebSphere Commerce product suites and other web technologies such as Java, J2EE/JEE, Spring, PHP, WordPress and more. Twitter | Facebook | LinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *