Search code examples
javagwtuibinder

How to use @UiHandler with customized handler (pass constructor args)


Normally, we do this:

@UiHandler("aLink")
void onClickALink(ClickEvent e) {
    // do something
}

But, what if I want to use my own Handler implementation?

class MyClickHandler implements ClickHandler {
    int i;

    MyClickHandler(int i) {
        this.i = i;
    }

    @Override
    public void onClick(ClickEvent event) {
        // do something
    }
}

Then, how do I use MyClickHandler with @UiHandler? i.e. pass i to the constructor?


Solution

  • You need to create also a specific click event:

    class MyClickHandler implements ClickHandler {
        int i;
    
        MyClickHandler(int i) {
            this.i = i;
        }
    
        @Override
        public void onClick(MyClickEvent event) {  // MyClickEvent!
            // do something
        }
    }
    

    Then you can do:

    @UiHandler("aLink")
    void onClickALink(MyClickEvent e) {
        // do something
    }
    

    Make sure you implement all needed methods in MyClickEvent so that GWT can understand that it is associated to MyClickHandler: see ClickEvent dispatch(), getAssociatedType() and getType()

    For an example see how CustomEvent is implemented in HandlerDemo.java.

    Then, how do I use MyClickHandler with @UiHandler? i.e. pass i to the constructor?

    You don't.