Tuesday, August 17, 2010

Four easy steps to implementing a ClickHandler in a composite control.

After developing a composite control a click handler interface (ClickHandler) is required to respond to user events. A typically example might be the type of thing shown as a row in your Gmail email list. You have developed a control which nicely lays out all the relevant information in the row, but the row as a whole should fire a click event when clicked.

This kind of implementation is easy, but it can get confusing especially if you are new (like me) to this kind of expert level programming. So for my own benefit and yours this is how it is implemented.

Step 1 : Implement HasClickHandlers Interface
In the child composite control first implement the HasClickHandlers interface:

public class ApplicationMenuLink extends Composite implements HasClickHandlers {

Step 2 : Add the unimplemented methods

@Override
public HandlerRegistration addClickHandler(ClickHandler handler) {
  return addHandler(handler, ClickEvent.getType());
}

Step 3 : Fire the event when needed

@UiHandler("hyperlinkControlInComposite")
void doClick(ClickEvent e){
  this.fireEvent(e);
}

Step 4 : Implement handler in the parent control

instanceOfChildComposite.addClickHandler(new ClickHandler() {
  @Override
  public void onClick(ClickEvent event) {
    //Do Stuff
  }
}));

or using the UiHandler convention:

@UiHandler("instanceOfChildComposite")
void doClick(ClickEvent e){
  //Do Stuff
}

Conclusion
Et Voila! Thats all there is to it. As usual the path to this solution is a lot more tortuous than it would appear, but hopefully now I have it here it will be simpler for me and all us GWT developers.

5 comments:

  1. That UiHandler technique looks way more attractive to me. :-)

    ReplyDelete
  2. Great step-by-step. Saved me a lot of struggling

    ReplyDelete
  3. Cool, I posted an example similar to this one on Gwt-Platform mailing list lately. Only difference is that I made my own custom named event, because I had more than one click event to handle resulting in the impossibility to have only one HasClickHandlers. (Edit, save, delete) And well, I also need the right souce, and well the source of a click, if you don't fire it yourself, is the button itself instead of a row :D

    Anyway, nice post !

    Cheers,

    ReplyDelete
  4. Christian,

    Looks good. Do you have a link to the article. On the same subject there is also this article for creating a complete custom event and handler.

    http://www.gwtsushi.info/2010/07/how-to-create-custom-event-handler-in.html

    Cheers
    Gene

    ReplyDelete
  5. Here's the link of the discussion, there's a lot inside, but I think your article is the right post to start with as a complement for that discussion.

    http://groups.google.com/group/gwt-platform/browse_thread/thread/6eee2e443cd408c9

    Cheers,

    ReplyDelete