Creating class instances dynamically from loaded SWF's
DIGG IT!
3
Comments
Published
Wednesday, November 14, 2007
at
5:43 AM
.
A few days back I posted on a simple factory-like method for returning class instances from a loaded SWF file. At lunch yesterday with Matt Chotin he mentioned another way which I thought was worth posting. It seems that there is a property on Loader or SWFLoader called 'loaderContext' and in turn it has a property called 'applicationDomain' and this object has two methods worth knowing about 'hasDefinition' and 'getDefiniton'. Interesting! Here is how to use them:
Say I load a SWF9 file into a SWFLoader instance like so:
<SWFLoader id="contentLoader" url="content.swf"/>
In content.swf I have a class named 'Foo'. To create an instance of Foo dynamically I would do this:
if ( contentLoader.loaderContext.applicationDomain.hasDefinition('Foo')){
var FooClass:Class = contentLoader.loaderContext.applicationDomain.getDefinition('Foo') as Class;
var fooInstance:Object = new FooClass();
}
In this case hasDefinition return a boolean to tell if a class is present in the loaded SWF and if it is present we can obtain the Class using 'getDefinition'. Then by simply using new with the returned class you can create instances.
What I like about this is that you can obtain Class instances from any SWF9 file without additional code within the loaded SWF. The only downside is that there is no metadata within the SWF file listing the classes available. It would be easy to denote the classes in a SWF file with an array at the root of the loaded SWF file. Regardless, this is a great technique to know about. Kudos to Matt for pushing me deeper into the AS3 APIS.
Cheers,
Ted :)

Ted...
Really a nice Post. It's just like to get a Gem from the Ocean.
But I have to queries, and hope you can solve.
1) what is swf9 file.
2) The only downside is that there is no metadata within the SWF file listing the classes available. ===>>>
It would be easy to denote the classes in a SWF file with an array at the root of the loaded SWF file.
Can you throw some more light on, how to denote the classes in SWF file (and if you, how to read metadata within the SWF file)
Hey, very nice way of doing it, but unfortunately I couldn't get it to work with an embedded SWF file as the contentLoader/loaderInfo/etc. objects are all empty when it's embedded.
Do you think it's possible to do it ?
Right now I'm using your previous getInstance() method, which works well but this would be nicer so here I am.
Thanks.
I have tried this code but it doesn't work for me. I have Flex 2, Flash CS3. The swf is swf9 w/AS3 but 'hasDefinition' is always false weather i use library name, class name (setup in Linkage) or a stage instance name.
However, when i change it to:
swfTestLoader.content.loaderInfo
.applicationDomain.hasDefinition("TestClip")
it works for the class name (setup in the Linkage). Why would this code work for me while Ted's doesn't?? Whats the difference??
Cheers,
James