开发者

Preserving navigation/history state in GWT with MVP pattern

I've implemented a basic GWT app based on on the MVP pattern Google recommends. What I'm trying to figure out is the best way to store navigation/history state once you fill your application with data.

Let's say you have a search that returns a bunch data into a CellTable. If I navigate to a specific item in the search result to another panel, the initial Panel with the search result is gone unless the Presenter/View is stored somewhere so I 开发者_如何学Gocan access it easily on a back navigation.

So, my question is, what do apps like Gmail do to preserve the state for back navigation? Are there any examples of how this can be implemented?


Gmail doesn't use GWT, so I'm assuming you just want a high-level answer.

Gmail uses the URL fragment (the part after the #). As you navigate around in Gmail you'll notice that the fragment changes to a unique identifier for each "location" in Gmail's navigation. Using the fragment makes the browser do all the tracking for you without requiring page reloads. You then just monitor the fragment, and when it changes you navigate to the location it specifies.


There are several MVP library projects for GWT that use the concept of a Place to represent the state of Presenters. Place implementations generally map the state to the URL fragment after the #. Hence, they work similarly to Gmail's state handling.

As an example, using the gwt-presenter project, you may have a DataPresenter and a DataPlace:

public class DataPlace extends ProvidedPresenterPlace<DataPresenter> {

@Inject
public DataPlace(Provider<DataPresenter> presenter) {
    super(presenter);
}

@Override
public String getName() {
    return "data";
}

@Override
protected void preparePresenter( PlaceRequest request, DataPresenter presenter ) {
    String state = request.getParameter("state", null);
    if (state != null) {
        // set the presenter state
        presenter.setState(State.valueOf(state));
    }
}

@Override
protected PlaceRequest prepareRequest( PlaceRequest request, DataPresenter presenter ) {
    return request.with("state", presenter.getState().toString());
}
}

When the URL has the form /data#state=12345, this Place will be asked to prepare the Presenter based on the parameters. Afterwards, the reveal method in the Presenter will be invoked. Since the state was already prepared by the Place, you'll be able to restore the view as needed.


Where do you create Activities? You should return an existing activity instead of creating a new one every time a place changes. Activities are usually created in ActivityMapper. You have two options:

  1. Change ActivityMapper so that it creates an Activity instance on first invocation, and return this instance on subsequent invocations. Or,

  2. Use CachingActivityMapper to wrap your ActivityMapper. It will return an existing Activity instead of creating a new one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜