I had a problem trying to load external classes in ActionScript 3.0. I believe this is a problem with my understanding of the ApplicationDomain / LoaderContext classes, but even after looking at the documentation and a few web searches, I'm still stuck.
Essentially, I want to load swf, which contains a character, which is an implementation of an interface shared by calling swf and loaded swf. I can load swf fine and create instances and execute methods on it, but only until I try to pass it into a common interface type. If I try to execute it, I get TypeError: Error # 1034: Type Coercion failed: enter an error.
I suspected that this was due to the fact that when loading a new class, flash recognizes it as a completely different class, therefore an exception. The documentation suggests using the LoaderContext argument, and applicationDomain - ApplicationDomain.currentDomain.
The problem is that this has no effect. Regardless of whether I set ApplicationDomain to currentDomain, null or a child of the current domain, I still get a forced type error. It seems that the :: error part indicates that the class I loaded is in a different namespace or in some such cases when I want it to be in the same namespace as my loader.
The code:
import flash.display.Loader;
import flash.display.MovieClip;
import flash.events.Event;
import flash.net.URLRequest;
import flash.system.ApplicationDomain;
import flash.system.LoaderContext;
public class TestSkin extends MovieClip
{
var mLoader:Loader;
public function TestSkin()
{
super();
startLoad("ExternalTest.swf");
}
private function startLoad(url:String):void
{
mLoader = new Loader();
var mRequest:URLRequest = new URLRequest(url);
var appDomain:ApplicationDomain = ApplicationDomain.currentDomain;
mLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onCompleteHandler);
mLoader.load(mRequest, new LoaderContext(false, appDomain));
}
private function onCompleteHandler(loadEvent:Event):void
{
var obj:Object = loadEvent.target.content;
trace("Loaded item id: " + obj.getInterfaceId());
var castItem:TestInterface = TestInterface(obj);
trace("castItem: " + castItem);
}
}
Interface declaration:
public interface TestInterface
{
function getInterfaceId():String;
}
Interface execution
public class ExternalTestInterfaceImplementation extends MovieClip implements TestInterface
{
public function getInterfaceId() : String
{
return "ExternalTestInterfaceImplementation!";
}
public override function toString():String
{
return getInterfaceId();
}
}