Search code examples
actionscript-3class-designaddeventlistener

addEventListener for a Function in a Different Class


Quick ActionScript question, since I'm still getting used to the language:

Is it possible to pass addEventListener a function that is in a different class? I.E. I have Model call addEventListener(Event.NAME, Controller.function) or something along those lines.

Probably not a big deal if I can't do this, but I was just wondering for the sake of code organization etc.


Solution

  • Yes you can as you can see in the following example I made:

    package 
    {
        import flash.display.Sprite;
        import flash.events.Event;
    
        public class Main extends Sprite 
        {
    
            public function Main():void 
            {
                if (stage) init();
                else addEventListener(Event.ADDED_TO_STAGE, init);
            }
    
            private function init(e:Event = null):void 
            {
                removeEventListener(Event.ADDED_TO_STAGE, init);
    
                addChild(new CustomSprite);
    
            }// end function
    
        }// end class
    
    }// end package
    
    import flash.events.Event;
    import flash.display.Sprite;
    
    internal class Global
    {
        public static function onAddedToStage(e:Event):void
        {
            trace("onAddedToStage() called.");
    
        }// end function
    
    }// end class
    
    internal class CustomSprite extends Sprite
    {
        public function CustomSprite()
        {
            addEventListener(Event.ADDED_TO_STAGE, Global.onAddedToStage);
    
        }// end function
    
    }// end function
    

    Personally I wouldn't suggest it though, although it could have some interesting applications.