George
George

Reputation: 15551

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

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.

Upvotes: 2

Views: 6327

Answers (2)

Jacob Poul Richardt
Jacob Poul Richardt

Reputation: 3143

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.

Upvotes: 6

Jeremy Stanley
Jeremy Stanley

Reputation: 5926

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

Upvotes: 1

Related Questions