views:

204

answers:

1

I want to remove a GWT event handler the first time I receive an event. I also want to avoid polluting my class with tracking registration objects that aren't really necessary. I currently have it coded as:

final HandlerRegistration[] registrationRef = new HandlerRegistration[1];
registrationRef[0] = dialog.addFooHandler(new FooHandler()
{
    public void onFoo(FooEvent event)
    {
        HandlerRegistration removeMe = registrationRef[0];
        if(removeMe != null)
        {
            removeMe.removeHandler();
        }

        // do stuff here
    }
});

but the use of registrationRef makes the code less readable. Is there a better way to do this without adding variables to my class?

+1  A: 

I'd just make the HandlerRegistration object a field of the enclosing class, that way you won't be bothered by the compiler and it's more "elegant" than shuffling arrays and stuff:

public class TestWidget extends Composite {
    //...

    HandlerRegistration handler;

    public TestWidget() {
        // ...

        handler = button.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                // ...
                handler.removeHandler();                
            }
        });
    }

}
Igor Klimer
Yes, thanks. I guess this is the way to go when you only have one of these listeners in a class (things get more messy when you have an arbitrary number of widgets you're treating this way though). I was hoping there was a way to do this without adding a new field. Oh well...
Keith