Accessing the Document class in AS3
Asked Answered
F

3

15

How can instantiated classes access the Document class?

Even after I name the Document class using the Properties bar in Flash, attempting to access it from other classes usually fails, saying "attempting to access an undefined property...

One solution is always casting the Document class to itself! eg.

Main(Main).globalMethod();

But sometimes even this stellar gotcha fails, and then there's usually no way out, apart from the obvious!

class Other{

   var parentClass:Main;
   public function Other(parent:Main){
       parentClass = parent;            // pointer to the Main class in a local var!

       Main(parentClass).globalMethod();
   }
}
Fragmental answered 16/12, 2008 at 0:59 Comment(0)
I
22

You can use a singleton for your document class (Main, in your example), which allows you to access the instance from anywhere.

public class Main extends Sprite {
    private static var _instance:Main;
    public static function get instance():Main { return _instance; }

    public function Main() {
        _instance = this;
       // etc...
    }

    // etc...
}

Then you access the Main instance like this:

public class Other {
    public function Other() {
        Main.instance.usefulInstanceMethod();
    }
}

The document class is a pretty good candidate for the singleton pattern, because generally there should only be instance available.

Inkhorn answered 17/12, 2008 at 3:39 Comment(3)
Is the "instance()" property really necessary in the Main class? I mean can't you just access the "_instance" pointer variable?Fragmental
Thats not a Singleton, that is more of a Monostate.Parley
Jeremy: The instance property function just ensures that only the Main class could possibly change the private _instance var. Notice that there is no setter. Matt: Thank you for enlightening me.Inkhorn
P
4

The document class is not inherently a globally accessible object. If you want to call methods that are in the document class, you'll always have to pass a reference from Main to any other classes/objects that want to call its methods. A more object oriented approach would be to dispatch events from your other classes (Other) for the Main class to listen to and call an appropriate method in itself.

If you are unconcerned about keeping a good OOP structure and want to access the document class from a display object that has been added to the display list you could try something like: stage.getChildAt( 0 );

Parley answered 16/12, 2008 at 15:22 Comment(0)
K
4

Just a side note, but the shortest answer to this question is: the same way any class access any other class. That is, with either a direct reference or a static exposure. The document class is no different from any other class in this regard.

Khedive answered 18/12, 2008 at 2:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.