« GWT Pros and Cons | Main | Design Patterns and GWT »
Sunday
Apr192009

Binding the Model to the View in GWT

When you start creating a simple GWT widget, it is very tempting to keep all UI elements (view), the data (model), and the logic that manipulates the view and model (controller) in one place. When your app gets bigger, you end up creating a spaghetti code, especially when you want make an event to cause an update in a widget defined in another class. To untangle the mess, split the code into three logically separate parts: Model, View, and Controller.

To bind the data to the view:
The best solution is to register a ChangeListener in the Model and notify the View on change (this is what MVC pattern does). Ideally, you would split the code associated with a Widget into three separate classes. One would be a Controller, one a Model, and one a View.

  • The Model (the Observable) does not have any reference to the Controller or the View
  • The Controller has a reference to Model
  • The View has a reference to the Model (is able to add listeners to it) and the Controller
So what does View do?
  • It registers listeners with a Model, allowing the Model to fire onChange() events which the View can use to update itself.
  • It registers various listeners on its UI elements (ClickListener for a Button, etc) and defines the onClick() or such methods, where the calls to controller are made.
  • When the user clicks on an UI element, the controller method is called and performs the necessary computation and/or updates the model.
What does Controller do?
  • Exposes various public methods that perform computations and manipulate the data in a Model
  • Controller does not update the View directly. It updates the Model which View listens to.
What does Model do?
  • Allows to register change listeners via addChangeListener()
  • It contains the state of the data, and fires the onChange events when Controller calls its setter methods
This decoupling of the model, view, and controller allows better reusability of code, as well as testability. You do not need to extend (the painfully slow to use) GwtTestCase to test the code in Model or Controller. You simply extend the junit.framework.TestCase and you can use any Java library, not only those supported by GWT.

EmailEmail Article to Friend

Reader Comments (1)

Vzor-Pohľad-Dozorca
Ah, now I finally understand...

April 26, 2009 | Unregistered CommenterKarol

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>