Search code examples
actionscript-3globalentry-point

Is there a way to access entry point class object from other classes of the app?


Just wonder if I can reference entry point object from any place in the app? Is it maybe assigned to some global object, like stage is for example?

Currently I use static methods and variables, but this breaks encapsulation.


Solution

  • If someObject is in display list, then you have a someObject.root reference which is what you are looking for. If you remove someObject from display list, you loose that reference.

    My answer is no, there is no direct way to access entry object, and there shouldn't be: that's what incapsulation is about. Accessing something globally is pretty much AS1 way. When you access main instance by implicitly referencing MainClass, you make parts of your application tightly coupled, which is generally bad.

    However, if you do need to have it, you may choose from several options.

    • Use static var: MainClass.instance
    • Use singletone-like access through MainClass.getInstance()
    • Create a package-level variable or a package level getter method

    I would choose the latter.

    package com.smth.application 
    {
        public var mainObject:MainClass;
    } 
    
    // in main app
    package com.smth.application 
    {
        public function MainClass()
        {
            mainObject = this;
        }
    }
    

    It may look somewhat similar to static acces, but I think this way your code will retain some flexibility.