stage.addEventListener inside a package?

瘦欲@ 提交于 2019-12-08 13:33:12

问题


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.


回答1:


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");
        }

    }
}



回答2:


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...



来源:https://stackoverflow.com/questions/4552210/stage-addeventlistener-inside-a-package

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!