ViewとLogicを分離する方法(1) - アプリケーションクラスを拡張する

 ※これはFlexの話です

 まず、ビュー側。

 mx:Applicationタグの代わりにmy:HelloLogicタグを使う。
 xmlns:my属性に「my」という名前空間を定義しておく。

 [View] HelloView.mxml

<?xml version="1.0" encoding="utf-8"?>
<my:HelloLogic
    xmlns:mx="http://www.adobe.com/2006/mxml"
    xmlns:my="jp.seagirl.labs.learning.*"
    layout="absolute">
    <mx:VBox x="10" y="10">
        <mx:Text id="title" text="Test"/>
        <mx:Button id="btn" label="Click me!"/>
        <mx:Text id="txt" fontSize="100"/>
    </mx:VBox>
</my:HelloLogic>


 次に、ロジック側。

 ビュー側で定義した名前空間にHelloLogicクラスを作る。
 このクラスはmx.core.Aplicationのサブクラスにする。
 コンストラクタでFlexEvent.CREATION_COMPLETEを拾ってやって、init()を呼ぶ。
 後の処理はinit()以降に書く。
 this['']でビューに書いたコンポーネントにアクセス出来る。

 [Logic] jp/seagirl/labs/learning/HelloLogic.as

package jp.seagirl.labs.learning
{    
    import flash.events.MouseEvent;

    import mx.core.Application;
    import mx.events.FlexEvent;

    public class HelloLogic extends mx.core.Application
    {    
        //----------------------------------------------------------------
        //
        //  Constructor
        //
        //----------------------------------------------------------------
        
        public function HelloLogic()
        {    
            super();
            addEventListener(FlexEvent.CREATION_COMPLETE, creationCompleteHandler);
        }
        
        //----------------------------------------------------------------
        //
        //  Initialize
        //
        //----------------------------------------------------------------
        
        private function init():void
        {
            this['btn'].addEventListener(MouseEvent.CLICK, btnClickHandler);
        }
        
        //----------------------------------------------------------------
        //
        //  Event Handlers
        //
        //----------------------------------------------------------------
        
        private function creationCompleteHandler(event:FlexEvent):void
        {
            init();
        }
        
        private function btnClickHandler(event:MouseEvent):void
        {
            this['text'].text = 'Hello World!!';
        }
    }
}