As3 declaring a GLOBAL variable – in TIMELINE / outside of CLASS

actionscript-3flashglobalglobal-variablesscope

I am looking to declare a GLOBAL VAR in the main time line.

Then I need to access that GLOBAL VAR from another externally loaded SWF's.

QUESTIONS:

How do I create the global var in the main timeline?

How do I access that var in externally loaded swf files?

Best Answer

First, you shouldn't use any global/static state. In your situation this is even more true, because Singletons are a royal pain in the butt across different applicationDomains.

Instead, you should use something called Dependency Injection. Think of your little swfs as starving orphans. When they have loaded, they don't run up to your main swf and pick its pockets. Instead, the main swf magnanimously presses money into their little hands.

So, how do we make this happen? One way is that we could compile a reference to their Document class(es) into the main swf, and then we could set a variable that the Class exposes. However, this can get pretty heavy and isn't really necessary.

Instead, you can write something called an Interface, which defines the "idea" of an orphan.

It might look something like this:

public interface IOrphan {
   function get alms():Number;
   function set alms(value:Number):void;
}

Note that you have to use getters and setters with Interfaces, because you can't use them to define vanilla variables. However, that's going to work out great for our actual Orphan:

public class Oliver implements IOrphan {
    private var _alms:Number;
    private var _totalAlms:Number;
    public var tf:TextField;//put this on stage and allow Flash to populate automatically
    public function get alms():Number {
       return _alms;
    }
    public function set alms (value:Number):void {
      _alms = value;
      _totalAlms += _alms;
      updateAlmsMessage();
    }
    private function updateAlmsMessage():void {
       tf.text = 'That was a donation of ' + _alms + '.\n'
                 'I now have ' _totalAlms + '.\n'
                 'Please, sir, can I have some more?';
    }
}

Now, all you need to do is populate that variable on load. There are several ways you can do this, such as watching the stage for IOlivers to be loaded, or you could be more direct about it:

private function loadSwf(url:String):void {
            var loader:Loader = new Loader();
            loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
            var request:URLRequest = new URLRequest(url);
            loader.load(request);
            addChild(loader);
}

private function completeHandler(e:Event):void {
   ((e.target as LoaderInfo).content as IOrphan).alms = .25;
}