Skip to main content

Home/ GWT - MVP/ Group items tagged UiHandler

Rss Feed Group items tagged

Marco Antonio Almeida

GWT MVP Development with Activities and Places - Google Web Toolkit - Google Code - 2 views

  • An activity in GWT 2.1 is analogous to a presenter in MVP terminology. It contains no Widgets or UI code. Activities are started and stopped by an ActivityManager associated with a container Widget. A powerful new feature in GWT 2.1 is that an Activity can automatically display a warning confirmation when the Activity is about to be stopped (such as when the user navigates to a new Place). In addition, the ActivityManager warns the user before the window is about to be closed.
  • A place in GWT 2.1 is a Java object representing a particular state of the UI. A Place can be converted to and from a URL history token (see GWT's History object) by defining a PlaceTokenizer for each Place, and the PlaceHistoryHandler automatically updates the browser URL corresponding to each Place in your app.
  • A key concept of MVP development is that a view is defined by an interface.
  • ...23 more annotations...
  • It is useful for views to extend IsWidget if they do in fact provide a Widget.
  • more complicated view that additionally defines an interface for its corresponding presenter (activity)
  • The Presenter interface and setPresenter method allow for bi-directional communication between view and presenter,
  •   @UiHandler("goodbyeLink")        void onClickGoodbye(ClickEvent e) {                presenter.goTo(new GoodbyePlace(name));        }
  • Because Widget creation involves DOM operations, views are relatively expensive to create. It is therefore good practice to make them reusable, and a relatively easy way to do this is via a view factory, which might be part of a larger ClientFactory.
  • Note the use of @UiHandler that delegates to the presenter
  • Another advantage of using a ClientFactory is that you can use it with GWT deferred binding to use different implementation classes based on user.agent or other properties. For example, you might use a MobileClientFactory to provide different view implementations than the default DesktopClientFactory.
  • ClientFactory A ClientFactory is not strictly required in GWT 2.1; however, it is helpful to use a factory or dependency injection framework like GIN to obtain references to objects needed throughout your application like the event bus.
  • Specify the implementation class in .gwt.xml:     <!-- Use ClientFactoryImpl by default -->    <replace-with class="com.hellomvp.client.ClientFactoryImpl">    <when-type-is class="com.hellomvp.client.ClientFactory"/>    </replace-with> You can use <when-property-is> to specify different implementations based on user.agent, locale, or other properties you define.
  • Activities Activity classes implement com.google.gwt.app.place.Activity. For convenience, you can extend AbstractActivity, which provides default (null) implementations of all required methods.
  • The first thing to notice is that HelloActivity makes reference to HelloView. This is a view interface, not an implementation.
  • The HelloActivity constructor takes two arguments: a HelloPlace and the ClientFactory
  • In GWT 2.1, activities are designed to be disposable, whereas views, which are more expensive to create due to the DOM calls required, should be reusable. In keeping with this idea, ClientFactory is used by HelloActivity to obtain a reference to the HelloView as well as the EventBus and PlaceController.
  • Finally, the goTo() method invokes the PlaceController to navigate to a new Place. PlaceController in turn notifies the ActivityManager to stop the current Activity, find and start the Activity associated with the new Place, and update the URL in PlaceHistoryHandler.
  • The non-null mayStop() method provides a warning that will be shown to the user when the Activity is about to be stopped due to window closing or navigation to another Place. If it returns null, no such warning will be shown.
  • In order to be accessible via a URL, an Activity needs a corresponding Place. A Place extends com.google.gwt.app.place.Place and must have an associated PlaceTokenizer which knows how to serialize the Place's state to a URL token.
  • It is convenient (though not required) to declare the PlaceTokenizer as a static class inside the corresponding Place. However, you need not have a PlaceTokenizer for each Place. Many Places in your app might not save any state to the URL, so they could just extend a BasicPlace which declares a PlaceTokenizer that returns a null token.
  • For even more control, you can instead implement PlaceHistoryMapperWithFactory and provide a TokenizerFactory that, in turn, provides individual PlaceTokenizers.
  • For more control of the PlaceHistoryMapper, you can use the @Prefix annotation on a PlaceTokenizer to change the first part of the URL associated with the Place
  • PlaceHistoryMapper PlaceHistoryMapper declares all the Places available in your app. You create an interface that extends PlaceHistoryMapper and uses the annotation @WithTokenizers to list each of your tokenizer classes.
  • ActivityMapper Finally, your app's ActivityMapper maps each Place to its corresponding Activity. It must implement ActivityMapper, and will likely have lots of code like "if (place instanceof SomePlace) return new SomeActivity(place)".
  • How it all works The ActivityManager keeps track of all Activities running within the context of one container widget. It listens for PlaceChangeRequestEvents and notifies the current activity when a new Place has been requested.
  • To navigate to a new Place in your application, call the goTo() method on your PlaceController.
Esfand S

Large scale application development and MVP - Part II - 0 views

  • segment the code that declares the UI from the code that drives the UI.
  • we want the our ContactsPresenter to implement a Presenter interface that allows our ContactsView to callback into the presenter when it receives a click, select or other event. The Presenter interface defines the following:   public interface Presenter<T> {    void onAddButtonClicked();    void onDeleteButtonClicked();    void onItemClicked(T clickedItem);    void onItemSelected(T selectedItem);  }
  • The first part of wiring everything up is to have our ContactsPresenter implement the Presenter interface, and then register itself with the underlying view. To register itself, we'll need our ContactsView to expose a setPresenter() method:   private Presenter<T> presenter;  public void setPresenter(Presenter<T> presenter) {    this.presenter = presenter;  }
  • ...8 more annotations...
  • With the ColumnDefinition(s) in place, we will start to see the fruits of our labor. Mainly in the way we pass model data to the view. As mentioned above we were previously dumbing down the model into a list of Strings. With our ColumnDefinition(s) we can pass the model untouched.   public class ContactsPresenter implements Presenter,    ...    private void fetchContactDetails() {      rpcService.getContactDetails(new AsyncCallback<ArrayList<ContactDetails>>() {        public void onSuccess(ArrayList<ContactDetails> result) {            contactDetails = result;            sortContactDetails();            view.setRowData(contactDetails);        }        ...      });    }    ...  } And our ContactsViewImpl has the following setRowData() implementation:   public class ContactsViewImpl<T> extends Composite implements ContactsView<T> {    ...    public void setRowData(List<T> rowData) {      contactsTable.removeAllRows();      this.rowData = rowData;      for (int i = 0; i < rowData.size(); ++i) {        T t = rowData.get(i);        for (int j = 0; j < columnDefinitions.size(); ++j) {          ColumnDefinition<T> columnDefinition = columnDefinitions.get(j);          contactsTable.setWidget(i, j, columnDefinition.render(t));        }      }    }    ...  } A definite improvement; the presenter can pass the model untouched and the view has no rendering code that we would otherwise need to test.
  • Note that our ContactsView is now ContactsViewImpl<T> and implements ContactsView<T>. This is so that we can pass in a mocked ContactsView instance when testing our ContactsPresenter. Now in our AppController, when we create the ContactsView, we can initialize it with the necessary ColumnDefinition(s).
  • Our current solution is to have our presenters pass a dumbed down version of the model to our views. In the case of our ContactsView, the presenter takes a list of DTOs (Data Transfer Objects) and constructs a list of Strings that it then passes to the view. public ContactsPresenter implements Presenter {  ...  public void onSuccess(ArrayList<ContactDetails> result) {    contactDetails = result;    sortContactDetails();    List<String> data = new ArrayList<String>();    for (int i = 0; i < result.size(); ++i) {      data.add(contactDetails.get(i).getDisplayName());    }    display.setData(data);  }  ...} The "data" object that is passed to the view is a very (and I mean very) simplistic ViewModel — basically a representation of a more complex data model using primitives. This is fine for a simplistic view, but as soon as you start to do something more complex, you quickly realize that something has to give. Either the presenter needs to know more about the view (making it hard to swap out views for other platforms), or the view needs to know more about the data model (ultimately making your view smarter, thus requiring more GwtTestCases). The solution is to use generics along with a third party that abstracts any knowledge of a cell's data type, as well as how that data type is rendered.
  • We've figured out how to create the foundation for complex UIs while sticking to our requirement that the view remain as dumb (and minimally testable) as possible, but that's no reason to stop. While functionality is decoupled, there is still room for optimization. Having the ColumnDefinition create a new widget for each cell is too heavy, and can quickly lead to performance degradation as your application grows. The two leading factors of this degradation are: Inefficiencies related to inserting new elements via DOM manipulation Overhead associated with sinking events per Widget To overcome this we will update our application to do the following (in respective order): Replace our FlexTable implementation with an HTML widget that we'll populate by calling setHTML(), effectively batching all DOM manipulation into a single call. Reduce the event overhead by sinking events on the HTML widget, rather than the individual cells. The changes are encompassed within our ContactsView.ui.xml file, as well as our setRowData() and onTableClicked() methods. First we'll need to update our ContactsView.ui.xml file to use a HTML widget rather than a FlexTable widget.
  • The above code is similar to our original setRowData() method, we iterate through the rowData and for each item ask our column definitions to render accordingly. The main differences being that a) we're expecting each column definition to render itself into the StringBuilder rather than passing back a full-on widget, and b) we're calling setHTML on a HTML widget rather than calling setWidget on a FlexTable. This will decrease your load time, especially as your tables start to grow.
  • To reiterate, we're reducing the overhead of sinking events on per-cell widgets, and instead sinking on a single container, our HTML widget. The ClickEvents are still wired up via our UiHandler annotations, but with this approach, we're going to get the Element that was clicked on and walk the DOM until we find a parent TableCellElement. From there we can determine the row, and thus the corresponding rowData.
  • Code Splitting is the act of wrapping segmented pieces of your application into "split" points by declaring them within a runAsync() call. As long as the split portion of your code is purely segmented, and not referenced by other parts of the app, it will be downloaded and executed at the point that it needs to run.
  •         // TODO: Really total hack! There's gotta be a better way...        Element child = cell.getFirstChildElement();        if (child != null) {          Event.sinkEvents(child, Event.ONFOCUS | Event.ONBLUR);        }
1 - 6 of 6
Showing 20 items per page