新規プレゼンタの作成
本来であればGWTPのEclipseプラグインを道入すれば、簡単にPresenter及びViewが作成されるはずだが、現在(2011/11/28)うまく動作していない。ここでは、手作業で新たなプレゼンタを作成してみる。
なお、前提として、Eclipseプラグインの「GWTP Project」でプロジェクトを作成する際に、「Generate gwtp-sample-basic」を選択してサンプルコードを生成済みであるとする。
基本的なステップ
ここでは、ごく基本的なステップで最低限の表示ができるまでを記述する。なお、パッケージ名の上位部分は省略している。
NameTokensへの追加
- Presenterの作成
- Viewの作成
ClientModuleへの追加
- Injectorへの追加
NameTokensへの追加
client.place.NameTokensクラスにPlaceの名称を登録する。Placeというのは、いわばGWTP内でページ切り替えを行う場合の「ページ」にあたる。 GWTでは、基本的に使用するhtmlページはただ一つだけで、その中で仮想的なページ切り替えを行うが、それをPlaceと称している。
public class NameTokens { public static final String main = "main"; public static final String response = "response"; public static final String something = "something"; ...
他のPlaceにならってgetSomething()などのメソッドを付加する必要は無い。
Presenterの作成
Presenterは、MVCを改良したMVPモデルのPにあたる。簡単に言えばコントローラの役割である。 Presenterの名称は慣習的にPresenterで終了しなければならない。
SomethingPresenter.java
package ....client.core; import com.cm55.gwtp.client.place.*; import com.google.gwt.event.shared.*; import com.google.inject.*; import com.gwtplatform.dispatch.shared.*; import com.gwtplatform.mvp.client.*; import com.gwtplatform.mvp.client.annotations.*; import com.gwtplatform.mvp.client.proxy.*; public class SomethingPresenter extends Presenter<SomethingPresenter.MyView, SomethingPresenter.MyProxy> { @ProxyStandard @NameToken(NameTokens.something) public interface MyProxy extends ProxyPlace<SomethingPresenter> {} public interface MyView extends View {} @Inject public SomethingPresenter(final EventBus eventBus, final MyView view, final MyProxy proxy, final DispatchAsync dispatcher, final PlaceManager placeManager) { super(eventBus, view, proxy); } @Override protected void revealInParent() { RevealRootContentEvent.fire(this, this); } }
特にMyProxyにつけられている@NameTokenは重要。この引数を間違えると動作しない。
Viewの作成
ViewはGUI部分になる。これにはSomethingPresenter.MyViewを実装させる。
package ......client.core; import com.google.gwt.user.client.ui.*; import com.google.inject.*; import com.gwtplatform.mvp.client.*; public class SomethingView extends ViewImpl implements SomethingPresenter.MyView { private static String html = "<div id=\"something\"></div>\n"; private final HTMLPanel panel = new HTMLPanel(html); @Inject public SomethingView() { Button someButton = new Button("do something"); panel.add(someButton, "something"); } @Override public Widget asWidget() { return panel; } }
ClientModuleへの追加
client.gin.ClientModuleのconfigure()メソッドに以下を追加して、GINがこれらを扱えるようにする。
bindPresenter(SomethingPresenter.class, SomethingPresenter.MyView.class, SomethingView.class, SomethingPresenter.MyProxy.class);
Injectorへの追加
client.gin.ClientGinjectorに以下を追加し、SomethingPresenterを注入できるようにする。
Provider<SomethingPresenter>getSomethingPresenter();