简体   繁体   中英

GWT Activities: Widget added to view again when using browser back button

The way I understand it, if I want to add widgets dynamically to a view created with UIBinder, I would do that in the start method of the activity that is the presenter for that view.

Here's my code:

@Override
public void start(AcceptsOneWidget panel, EventBus eventBus) {
    view = clientFactory.getDashboardView();
    view.setPresenter(this);

    ArrayList<Department> deps = ModelFactory.getDepartments();
    view.passData(deps); // Correct?
    panel.setWidget(view.asWidget());

}



public void passData(ArrayList<Department> departments) {

TextCell text = new TextCell();
CellList<String> cellList = new CellList<String>(text);
String[] departmentNames = new String[departments.size()];
for (int i = 0; i < departments.size(); i++) {
    departmentNames[i] = departments.get(i).getName();
}
cellList.setRowData(Arrays.asList(departmentNames));
departmentsDiv.add(cellList);

}

It works. However, when using the back button to navigate to the previous place and back, the widget is added again.

How do I handle this correctly?

You have two options:

  1. If you don't want to refresh the data on each visit to this view, you need to add a flag to the view to tell if the data has been already populated. Then, when this view is visited again, your activity should call view.passData(deps); only if the flag is set to false. After the data is loaded, set the flag to true.

  2. If you do want to refresh the data on each visit, call departmentsDiv.clear() before adding a new CellList.

NB: A better approach is to create your CellList once, when the view is displayed for the first time, and then only call setRowData when the new data is available.

You are creating View object by using Factory method. You should consider creating views during application load using, for instance: GIN and marking them as Singletons. The proper way is to pass them as start() method parameters and just set presenter reference on them.

General idea is to make Views singletons. Activities should be created while throwing GWT place (stateless) and just using singleton Views, so you can keep your view input data.

Read tutorial here on using MVP / GIN pattern: http://blog.hivedevelopment.co.uk/2009/08/google-web-toolkit-gwt-mvp-example.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM