Event#targetとcurrentTarget

by takasho
[ActionScript 3.0] Event#targetとcurrentTarget

イベントをリスナーで受け取ったとき、Event#targetとEvent#currentTargetの指し示すものが異なる場合がある。特にMouseEventでは注意が必要。

http://www28.atpages.jp/~oukastudio/wordpress/?p=108
♥1 | Line 34 | Modified 2011-07-26 10:40:35 | MIT License
play

ActionScript3 source code

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

package {
    import flash.text.TextFieldAutoSize;
    import flash.text.TextField;
    import flash.events.MouseEvent;
    import flash.display.Sprite;
    
    public class FlashTest extends Sprite {
        public function FlashTest() {
            var textCurTarget:TextField = new TextField;
            textCurTarget.autoSize = TextFieldAutoSize.LEFT;
            textCurTarget.y = 75;
            
            var textTarget:TextField = new TextField;
            textTarget.autoSize = TextFieldAutoSize.LEFT;
            textTarget.y = 90;
           
            var child:Sprite = new Sprite;
            child.graphics.beginFill(0);
            child.graphics.drawRect(20, 20, 20, 20);
            
            var parent:Sprite = new Sprite;
            parent.graphics.beginFill(0x0000ff, 0.5);
            parent.graphics.drawRect(20, 20, 50, 50);
            
            parent.addChild(child);
            
            parent.addEventListener(MouseEvent.CLICK,
                function (e:MouseEvent):void {
                    if (e.target == parent) textCurTarget.text = "e.target is parent";
                    else textCurTarget.text = "e.target is child";
                    
                    if (e.currentTarget == parent) textTarget.text = "e.currentTarget is parent";
                    else textTarget.text = "e.currentTarget is parent";
                }
            );
            
            addChild(parent);
            addChild(textCurTarget);
            addChild(textTarget);
        }
    }
}