GWTP get access from child presenter/view to parent presenter/view

538 Views Asked by At

I have 2 presenters/view. Lets call them parent and child. parent presenter is a container (using slot mechanism) for the child presenter. In the child presenter's view user clicked button and I would like to handle this action in parent presenter.

How can I do this? What is the best approach? Should I use some kind of event and eventhandler? Or should I inject one presenter to the other?

1

There are 1 best solutions below

2
Роман Гуйван On BEST ANSWER

Both are possible.

For events - GWTP have a simplified version of GWT events:

public interface MyEventHandler extends EventHandler {
    void onMyEvent(MyEvent event);
}

public class MyEvent extends GwtEvent<MyEventHandler> {
    public static Type<MyEventHandler> TYPE = new Type<MyEventHandler>();
    private Object myData;
    public Type<MyEventHandler> getAssociatedType() {
        return TYPE;
    }
    protected void dispatch(MyEventHandler handler) {
        handler.onMyEvent(this);
    }

    public MyEvent(Object myData) {
        this.myData = myData;
    }
    /*The cool thing*/
    public static void fire(HasHandlers source, Object myData){
        source.fireEvent(new MyEvent(myData));
    }
}

So in your child presenter you'll simply do:

MyEvent.fire(this, thatObjectYoudLikeToPass);

and to register it, in the parent, you'd either use:

addRegisteredHandler(MyEvent.TYPE, handler);

or

addVisibleHandler(MyEvent.TYPE, handler);

if you want it to be processed only when the parent is visible. I suggest you yo add these handlers in onBind method of your presenter (don't forget to call super.onBind() first when overriding)

For injection: Simply make sure:

  1. Your parent presenter is a singleton
  2. To avoid circular dependency error in GIN do not wire it like

    @Inject ParentPresenter presenter;

instead do it like this:

@Inject 
Provider<ParentPresenter> presenterProvider;

and access it with presenterProvider.get() in your child