001: /*
002: * MyGWT Widget Library
003: * Copyright(c) 2007, MyGWT.
004: * licensing@mygwt.net
005: *
006: * http://mygwt.net/license
007: */
008: package net.mygwt.ui.client.mvc;
009:
010: import java.util.ArrayList;
011: import java.util.HashSet;
012: import java.util.List;
013:
014: /**
015: * <code>Controllers</code> process and respond to application events.
016: */
017: public abstract class Controller {
018:
019: /**
020: * Forward an event to a view. Ensures the view is initialized before
021: * forwarding the event.
022: *
023: * @param view the view to forward the event
024: * @param event the event to be forwarded
025: */
026: public static void forwardToView(View view, AppEvent event) {
027: if (!view.initialized) {
028: view.initialize();
029: view.initialized = true;
030: }
031: view.handleEvent(event);
032: }
033:
034: protected Controller parent;
035: protected List children;
036:
037: boolean initialized;
038: private HashSet events;
039:
040: /**
041: * Add a child controller.
042: *
043: * @param controller the controller to added
044: */
045: public void addChild(Controller controller) {
046: if (children == null)
047: children = new ArrayList();
048: children.add(controller);
049: controller.parent = this ;
050: }
051:
052: /**
053: * Determines if the controller can handle the particular event. Default
054: * implementation checks against registered event types then queries all child
055: * controllers.
056: *
057: * @param event the event
058: * @return <code>true</code> if event can be handled, <code>false</code>
059: * otherwise
060: */
061: public boolean canHandle(AppEvent event) {
062: if (events != null && events.contains(new Integer(event.type)))
063: return true;
064: if (children != null) {
065: for (int i = 0; i < children.size(); i++) {
066: Controller c = (Controller) children.get(i);
067: if (c.canHandle(event))
068: return true;
069: }
070: }
071: return false;
072: }
073:
074: /**
075: * Forwards an event to any child controllers who can handle the event.
076: *
077: * @param event the event to forward
078: */
079: public void forwardToChild(AppEvent event) {
080: if (children != null) {
081: for (int i = 0; i < children.size(); i++) {
082: Controller c = (Controller) children.get(i);
083: if (!c.initialized) {
084: c.initialize();
085: c.initialized = true;
086: }
087: if (c.canHandle(event)) {
088: c.handleEvent(event);
089: }
090: }
091: }
092: }
093:
094: /**
095: * Processes the event.
096: *
097: * @param event the current event
098: */
099: public abstract void handleEvent(AppEvent event);
100:
101: /**
102: * Called once prior to handleEvent being called.
103: */
104: public void initialize() {
105:
106: }
107:
108: /**
109: * Registers the event type.
110: *
111: * @param type the event type
112: */
113: public void registerEventType(int type) {
114: if (events == null) {
115: events = new HashSet();
116: }
117: events.add(new Integer(type));
118: }
119:
120: }
|