All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.sencha.gxt.state.client.AbstractStateHandler Maven / Gradle / Ivy

/**
 * Ext GWT 3.0.0-beta2 - Ext for GWT
 * Copyright(c) 2007-2011, Sencha, Inc.
 * [email protected]
 *
 * http://sencha.com/license
 */
package com.sencha.gxt.state.client;

import com.google.gwt.core.client.Callback;

/**
 * Simple class to add support for reading and writing state. Can be subclassed
 * and a concrete type given to O (such as a Store or Component subclass), and a
 * particular interface S can be defined to hold the state for this object.
 * 
 * @param  the state interface
 * @param  the concrete type
 */
public abstract class AbstractStateHandler {
  private final Class stateType;
  private final O object;

  private final String key;

  private S state;

  protected AbstractStateHandler(Class stateType, O object, String key) {
    assert stateType.isInterface();

    this.stateType = stateType;
    this.object = object;

    this.key = key;

    state = StateManager.get().getDefaultStateInstance(stateType);
  }

  /**
   * Applies the currently loaded state to the current stateful object.
   * 
   * TODO fire a state restored event? allow this method to be canceled?
   */
  public abstract void applyState();

  public O getObject() {
    return object;
  }

  /**
   * @return the currently loaded state. The state instance may not be set, so
   *         this may return null.
   */
  public S getState() {
    return state;
  }

  /**
   * Starts to load the state for the given object.
   */
  public void loadState() {
    StateManager.get().get(key, stateType, new Callback() {
      @Override
      public void onFailure(Throwable reason) {

      }

      public void onSuccess(S result) {
        state = result;
        applyState();
      }
    });
  }

  /**
   * TODO fire a before event to allow it to be canceled? can this be deferred?
   *       fire an event when the save was successful?
   */
  public void saveState() {
    StateManager.get().set(key, state);
  }
}