AS3 ApplicationDomain misbehaves in subloaded SWF

Tuesday, December 20th, 2011

This post is not meant to be a comprehensive tutorial on Flash’s ApplicationDomain class and how it is used, for that I recommend Senocular’s excellent guide on the subject.  Rather, I just wanted to make a quick note of what I have observed when using ApplicationDomain.currentDomain in a subloaded SWF – that it doesn’t seem to work properly.

When I have a SWF that is loaded into another SWF, and it uses ApplicationDomain.currentDomain.getDefinition to grab a class from its own library, it fails with the following error: ReferenceError: Error #1065: Variable [VARIABLE_NAME] is not defined.  I assume that ApplicationDomain.currentDomain is mistakenly returning the parent SWF’s ApplicationDomain, instead of the child SWF, though I don’t really know why.

So here’s the quick fix, for those of you looking to cut to the chase: instead of using ApplicationDomain.currentDomain in your child SWF, use loaderInfo.applicationDomain instead.  This will explicitly grab the child SWF’s ApplicationDomain, not the parent’s, and your code will work as expected.  Note: I have not tested whether loaderInfo works as expected if your SWF is not subloaded, i.e. if it is the root SWF on the stage.

So to recap – when instantiating dynamic classes in a subloaded SWF, don’t use this:

ApplicationDomain.currentDomain.getDefinition

Rather, use this:

loaderInfo.applicationDomain.getDefinition

And save yourself the hassle I went through the last day or two!

AS3 for each … in vs for … in

Friday, December 16th, 2011

If you’re like me, remembering which version of the AS3 for … in loop does what is practically impossible.

So here is a reminder:

for each … in

Very simply, the for each … in loop iterates through the values of all properties associated with an object.

Example:

var obj:Object = {
  name:"Will Smith"
  occupation:"Actor"
};

for each (var prop in myObject){
trace(prop);
}

The above snippet will print the following:

Will Smith
Actor

for … in

Conversely, the for … in loop iterates through the name of each property associated with an object.

Example:

var obj:Object = {
  name:"Will Smith"
  occupation:"Actor"
};

for (var prop in myObject){
trace(prop);
}

The above snippet will print the following:

name
occupation

Hope this helps clear up some confusion!