stage.addEventListener inside a package?

2019-06-14 01:15发布

I am trying to do something like this:

package com.clicker{
    import flash.display.*;
    import flash.events.MouseEvent;

    public class Stager extends MovieClip {

        public function clicker():void {
            stage.addEventListener(MouseEvent.CLICK, do_stage);
        }
        function do_stage(e:MouseEvent):void {
            trace("stage clicked");
        }

    }
}

But, I get the 1009 error.

When I do this:

import com.clicker.*;

var test:Stager = new Stager();
test.clicker();
addChild(test); 

Please help me. Thank you very much in advance, and Happy Holidays.

2条回答
姐就是有狂的资本
2楼-- · 2019-06-14 01:34

since you call test.clicker(); before it added to the stage test doesn't have a this.stage object yet try :

public class Stager extends MovieClip {

    public function clicker():void {
       this.addEventListener( Event.ADDED_TO_STAGE , function(ev:Event) {
             stage.addEventListener(MouseEvent.CLICK, do_stage);
       });

    }
    function do_stage(e:MouseEvent):void {
        trace("stage clicked");
    }

}

hope this helps...

查看更多
走好不送
3楼-- · 2019-06-14 01:45

stage is accessible only when your component is added to the stage. If you want to know it, you can use the ADDED_TO_STAGE event.

So, you can do this :

package com.clicker{
    import flash.display.*;
    import flash.events.*;

    public class Stager extends MovieClip {

        public function clicker():void {
            addEventListener(Event.ADDED_TO_STAGE, init);
        }
        private function init(e:Event):void {
            removeEventListener(Event.ADDED_TO_STAGE, init);
            stage.addEventListener(MouseEvent.CLICK, do_stage);
        }
        function do_stage(e:MouseEvent):void {
            trace("stage clicked");
        }

    }
}
查看更多
登录 后发表回答