简体   繁体   中英

ADDED_TO_STAGE function never called

I have this class which should take a button from stage ( xBtn ).

package com.stx.utils {

    import flash.display.MovieClip;
    import flash.events.*;

    public class STXbutonx extends MovieClip {

        private var xBtn  : MovieClip;

        public function STXbutonx() {
            addEventListener(Event.ADDED_TO_STAGE, init);           
        }

        private function init(e:Event=null) : void {
            trace("int!"); //this is never called
            xBtn = stage.getChildByName('ics') as MovieClip;
            xBtn.addEventListener(MouseEvent.CLICK, onX);
            removeEventListener(Event.ADDED_TO_STAGE, init);
        }

        private function onX(e:MouseEvent) : void {
            trace("x Clicked!");
        }
    }
}

and in Document class I called like this :

import flash.display.MovieClip;
import com.stx.utils.*;

public class Main extends MovieClip {

    var xx : STXbutonx;

    public function Main() {    
        xx = new STXbutonx();
    }
}

Why my init function is never called?
Thank you!

Because you never add it to the stage.

Change your Document class to

public function Main() {    
    xx = new STXbutonx();
    addChild(xx);
}

Main holds the reference to the stage, adding a child to Main will add the child to the stage. Thus the event listener in STXbutonx will fire.


xBtn = stage.getChildByName('ics') as MovieClip; // now I have acces of undefined property stage...

You don't have access to the stage because STXButon is not on the stage, it is not an DisplayObject. To get around this, do this:

package com.stx.utils {

import flash.display.MovieClip;
import flash.events.*;

public class STXbutonx{

    private var xBtn  : MovieClip;
    private var stage : Stage;

    public function STXbutonx(stage:Stage) {
        this.stage = stage;
        init();           
    }

    private function init() : void {
        trace("int!");
        xBtn = stage.getChildByName('ics') as MovieClip;
        xBtn.addEventListener(MouseEvent.CLICK, onX);
        removeEventListener(Event.ADDED_TO_STAGE, init);
    }

    private function onX(e:MouseEvent) : void {
        trace("x Clicked!");
    }
}

}

And of course

import flash.display.MovieClip;
import com.stx.utils.*;

public class Main extends MovieClip {

var xx : STXbutonx;

public function Main() {    
    xx = new STXbutonx(stage);
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM