skip to main |
skip to sidebar
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: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 :)
2 Responses to “ Creating class instances dynamically from loaded SWF's ”