Friday, May 14, 2010

GWT: Dealing with the MenuBar inside MVP

Okay so I am trying to follow the MVP pattern of having a View interface that hides the details of the implementation. This has worked great up to the point where I need to add a MenuBar. Normally I would use on of the Has.... interfaces as a return value of a method on the view interface. The presenter then simply calls the getSomeAction().addHandler(....) but this doesn't exist for the MenuItem which uses the Command interface to respond to clicks on menus.

My first response was to create a component that encapsulated the Menu inside a control that had one button per menu item. The view interface could register click handlers by using the buttons on the menu and the menu items would simply fire the click() method on the buttons to execute all registered handlers.

Problem: Button.click() doesn't work if you have not added the Button to the DOM. I don't want the buttons in the DOM and it felt like a kluge to have the buttons in the DOM button hidden.

So my solution was to create a simple interface HasCommand that has one method setCommand.


public interface HasCommand{
setCommand(Command command);
}


Then I extended the MenuItem component overriding the 4 public constructors and implementing the new HasCommand interface. Now I simply use the HasCommand interface in my View definition and this makes it so I can sleep at night.

2 comments:

Syed Mahmood Ali said...

Could you please post the code?

Subhro said...

this helped. i was looking for a solution to this. thanks a lot for clarifying.