dispatchEvent について

by nbhd
■ dispatchEvent の検証
* イベントを登録する前にイベントを発行するメソッドを呼び出すと、リスナー関数が無視される。
* よくよく考えたら当り前のことか・・・。
♥0 | Line 31 | Modified 2009-06-12 17:58:49 | MIT License
play

ActionScript3 source code

/**
 * Copyright nbhd ( http://wonderfl.net/user/nbhd )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/f5gE
 */

/**
 * ■ dispatchEvent の検証
 * イベントを登録する前にイベントを発行するメソッドを呼び出すと、リスナー関数が無視される。
 * よくよく考えたら当り前のことか・・・。
 */
package {
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.text.TextField;
    
    public class FlashTest extends Sprite {
        
        private var _tf:TextField = new TextField();
        private var _foobar:FooBar = new FooBar();
        
        public function FlashTest() {
            
            addChild(_tf);
            
            //イベント登録の前に呼び出すとリスナーが効かない
            //_foobar.hogehoge("hoge");
            
            _foobar.addEventListener("piyo", _piyo);
            _tf.appendText("piyo : " + _foobar.willTrigger("piyo") + "\n");
            
            //イベント登録後に呼び出すと効く
            _foobar.hogehoge("hoge");
            
            _tf.appendText("piyo : " + _foobar.willTrigger("piyo") + "\n");
        }
        private function _piyo(e:Event):void{
            e.target.removeEventListener("piyo", _piyo);
            _tf.appendText("おしまい\n");
        }
    }
}

import flash.events.Event;
import flash.events.EventDispatcher;
class FooBar extends EventDispatcher{
    public function FooBar(){
    }
    
    public function hogehoge(_value:String):void{
        if(_value == "hoge") {
            dispatchEvent(new Event("piyo"));
        }
    }
}