Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

actionscript 3 - How do I access a movieClip on the stage using as3 class?

public class MyClass extends MovieClip {
            public function MyClass():void {
                my_mc.addEventListener(MouseEvent.CLICK, action);
            }
            private function action(e:MouseEvent):void {
                trace("cliked");
            }
        }

Timeline code

 var myClass:MyClass = new MyClass();
    addChild(myClass);

I can't able to access the my_mc(placed in FLA) movieclip. How do I access?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this:

public class MyClass extends MovieClip
{
    public function MyClass()
    {
        if (stage) init();
        else addEventListener(Event.ADDED_TO_STAGE, init);

    }// end function

    private function init(e:Event = null):void 
    {
        removeEventListener(Event.ADDED_TO_STAGE, init);

        var myMc:MovieClip = stage.getChildByName("my_mc") as MovieClip;
        // var myMc:MovieClip = parent.getChildByName("my_mc") as MovieClip;

        myMc.addEventListener(MouseEvent.CLICK, onMyMcClick)

    }// end function

    private function onMyMcClick(e:MouseEvent)
    {
        trace("clicked");

    }// end function

}// end class

If this doesn't work(which I don't think it will), its because your my_mc display object isn't a child of the stage, but the child of an instance of MainTimeline. If so, then simply comment out the following statement in the above code:

var myMc:MovieClip = stage.getChildByName("my_mc") as MovieClip;

and uncomment the following statement in the above code:

// var myMc:MovieClip = parent.getChildByName("my_mc") as MovieClip;

If my assumption is correct, the my_mc and myClass display objects share the same parent.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...