Actionscript3: how can I access elements on the stage from external classes?

孤街浪徒 提交于 2019-12-21 06:06:12

问题


I have an external class in a .as file, my problem is that I can't access elements on the stage. Code like stage.txtfield.text or this.parent.txtfield.text does not work. The txtfield is the instace name of a Dynamic Text field.


回答1:


It depends a bit on the external class.

If it extends DisplayObject (or any grandchild of DisplayObject), you will be able access with the stage property as soon as it is added to the display list (which is when it's added to the stage or any other DisplayObjectContainer on the display list).

To listen for that use the following code in the external class:

addEventListener(Event.ADDED_TO_STAGE, AddedToStage);

//...

private function AddedToStage(e:Event):void
{
    trace("TextField text" + TextField(stage["textfield"]).text);
}

If it not a displayObject or if it's not gonna be on the display list, the best thing would proberly be to give it the objects that it needs to access (like the TextField), in either the contructor or a seperate method call. You could give it a reference to the stage it self, but that wouldn't be very generic if for example you need the class to manipulate a TextField inside MovieClip.

You could give at reference to the TextField with this code:

//In any DisplayObject on the display list (could be inside a MovieClip or on the Stage itself)

var manipulator:MyClass = new MyClass(TextField(stage["textfield"]));

//In the external class

public class MyClass
{
    publich function MyClass(txt:TextField)
    {
        trace("TextField text" + txt.text);
    }
}

Mind you that this code doesn't check if the textfield is actually there. You should check that first and throw a proper error to make debugging easier.




回答2:


root and stage are no longer global, so you need to expose them via your document root class if you wish to use them in external classes.

Some reference: http://www.kirupa.com/forum/showthread.php?p=1952513



来源:https://stackoverflow.com/questions/716530/actionscript3-how-can-i-access-elements-on-the-stage-from-external-classes

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