Loading classes from external swfs can be very useful, especially as the size complexity of Flash and Flex applications are increasing. Including all the various tweening, 3D and util libraries can result in a very large swf file. Flash player 8.5 and above features a nifty API to dynamically load swfs and their classes at runtime, using the Loader and ApplicationDomain classes.
package com.welove72 {
import flash.display.Sprite;
public class Tracer extends Sprite {
public function Tracer():void { }
public function traceThis(strMessage:String):void {
trace(strMessage);
}
}
}
First, we create a simple class that includes a method traceThis to trace a message to the console. Add the code above to a new actionscript file called “Tracer.as†and save in the folder com/welove72. Create a new FLA and set the above class as the document class, “com.welove72.Tracerâ€. Save the file as Tracer.fla and hit Ctrl+Enter to create an swf.
package {
import flash.display.Loader;
import flash.net.URLRequest;
import flash.events.Event;
import flash.display.LoaderInfo;
import flash.display.MovieClip;
import flash.system.ApplicationDomain;
import flash.system.LoaderContext;
public class Main extends MovieClip {
public function Main():void {
var loader:Loader = new Loader();
var ldrContext:LoaderContext = new LoaderContext(false,
ApplicationDomain.currentDomain);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
loader.load(new URLRequest('Tracer.swf'), ldrContext);
}
private function onComplete(evt:Event):void {
var tracerClass:Class = ApplicationDomain.currentDomain.getDefinition
("com.welove72.Tracer") as Class;
var myTracer:* = new tracerClass();
myTracer.traceThis('Loaded a class!');
}
}
}
Add the code above to a new actionscript file called “Main.asâ€. Create another fla in the same location and save as Main.fla. Set Main as the document class, test the fla and you should see a message from the loaded Tracer class!
This tip and others from We Love are in the latest issue of Web Designer Magazine in the article “55 Pro Flash Tips”! Look out for Gavin Clark.