In an attempt to orient myself and my colleagues with GWT, I've been reading up on GWT, trying things out, and blogging about them here. My goal is to start with simple use cases and build on to them with more complex ones. The way it's been working so far is that each post builds on the prior one.

Wednesday, February 17, 2010

Improving the View with Composite Interfaces

Looking back at the ContactDetailPresenter code, there is missing logic based on the initial requirements of the Contact List application. The ContactDetailPresenter does not update the Contact’s first name when the user updates the first name in the UI. In the ContactDetailPresenter.setContact() method, we set up a ChangeHandler to create a ContactUpdatedEvent and post it to the event bus. The user initiates this by updating the first name of the Contact. The problem is that no code in the ChangeHandler actually pulled the updated first name off the View and applied it to the Contact. Unfortunately, the current structure of the View provides us no means to get that updated first name. All it currently supports is the ability to listen for when the name changed via its HasChangeHandlers interface:

public interface ContactDetailView {
public HasChangeHandlers setFirstName(String firstName);
}


We set the name, but all we get back in return is the ability to add listeners for the change. We also need that returned interface to support getting the text out of the UI element where the user entered the name. We’ll introduce a new interface, TextInput, which encapsulates both of these capabilities: TextInput now has capabilities to both add change handlers and get text.



public interface TextInput extends HasChangeHandlers, HasText{

}

Note: HasChangeHandlers and HasText are both interfaces delivered in the core GWT library.


And we’ll have ContactDetailView.setFirstName() return this expanded interface.



public interface ContactDetailView {
public TextInput setFirstName(String firstName);
}


With this new TextInput interface, we can fix the issue in our Presenter and have the ChangeHandler pull the text out of the TextInput interface and apply it to the Contact:




public void setContact(final Contact contact){
final TextInput textInput = view.setFirstName(contact.getFirstName());
textInput.addChangeHandler(new ChangeHandler() {

public void onChange(ChangeEvent event) {
contact.setFirstName(textInput.getText());
eventBus.fireEvent(new ContactUpdatedEvent(contact));
}
});
}


In this post we explored a pattern to create a composite interface to give parts of a View multiple capabilities. We do this to support how a Presenter needs to interact with its corresponding View.

No comments:

Post a Comment

Followers