Showing posts with label ClickHandler. Show all posts
Showing posts with label ClickHandler. Show all posts

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.