Posts Tagged: ‘PureMVC’

PureMVC for AS3

2013年6月23日 Posted by PURGE

元々Flexエンジニアだったので、PureMVCには以前から興味があったのだが、以前は時間の問題から諦めていた。PureMVCの本家サイトの情報も中々難解で、正直MVCの構造は理解できるのだが、フレームワークとしての定番の記述がよくわからず、具体的に記述でかなり迷っていた。

そこで改めてソースコードを整理してみた。但し、私のプログラムの記述が合っているとは思わないでほしい。

Main.mxml

  <s:WindowedApplication applicationComplete="facade.startup(this)">
  <fx:Script>
  <![CDATA[
    import com.whoocus.flex.ApplicationFacade;
    import mx.events.FlexEvent;
    // Initialize the PureMVC Facade
    private var facade:ApplicationFacade = ApplicationFacade.getInstance();			
  ]]>
  </fx:Script>

簡単に言うと、ApplicationFacadeのシングルトンクラスを呼び出す。
そのfacadeクラスのstartupメソッドででアプリをMainを登録して初期化処理が始まる。

ApplicationFacade.as

public class ApplicationFacade extends Facade
{
  /**
  * シングルトンのインスタンス生成取得メソッド
  */
  public static function getInstance( ) : ApplicationFacade 
  {
    if ( instance == null ) instance = new ApplicationFacade();
      return instance as ApplicationFacade;
    }
  /**
   * PureMVC アプリケーションのスタートアップメソッド 
   */
  public function startup( app:Main ):void
  {
    registerCommand( AppConstants.STARTUP, StartupCommand);
    sendNotification( AppConstants.STARTUP, app );
  }
}

startupメソッドのregisterCommandで、コマンドクラスを登録しsendoNotification通知を送信する。

StartupCommand.as

public class StartupCommand extends MacroCommand
{	
  override protected function initializeMacroCommand():void
  {
    addSubCommand(PrepareControllerCommand);
    addSubCommand(PrepareModelCommand);
    addSubCommand(PrepareViewCommand);
  }
}

StartupCommand内では、とりあえずcontroller/model/view の単位で登録するコマンドを小分けしている。

PrepareControllerCommand.as

public class PrepareControllerCommand extends SimpleCommand
{
  /**
   * Command登録処理
   */ 
  override public function execute(notification:INotification):void
  {
    //Command登録処理
    facade.registerCommand(AppConstants.HELLO, HelloCommand);
  }
}

PrepareControllerCommand.as

public class PrepareModelCommand extends SimpleCommand
{
  /**
   * Proxy登録処理
   */ 
  override public function execute(notification:INotification):void
  {
    //Proxy登録処理
    facade.registerProxy(helloProxy);
  }
}

PrepareViewCommand.as

public class PrepareControllerCommand extends SimpleCommand
{
  /**
   * Mediator登録処理
   */ 
  override public function execute(notification:INotification):void
  {
    //Mediator登録処理
    facade.registerMediator(new ApplicationMediator(app));
    facade.registerMediator(new HelloMediator(app.greeting));
  }
}