Flash AS3教程:ClassLoader类(2)
例子1:
图2
这是一个虚拟人物形象的动作包,其中包含了8种不同的动作
在使用ClassLoader加载这个swf的动作包后,即可使用getClass来调用这些素材,而且可以重复的new这些元件,来达到多次重复使用
import index.base.net.ClassLoader;
var cl:ClassLoader = new ClassLoader;
cl.load("main.swf");
cl.addEventListener(Event.COMPLETE,fun);
function fun(e:Event){
var tmp = cl.getClass("drag");
addChild(new tmp);
}
例子2:
将设我有一个类库,有这么三个类
然后把它编译成swf
我们另外建一个文件,来加载这个所谓的类库
import index.base.net.ClassLoader;
var cl:ClassLoader = new ClassLoader;
cl.load("main.swf");
cl.addEventListener(Event.COMPLETE,fun);
function fun(e:Event){
var tmp1 = cl.getClass("index.base.net.ByteLoader");
trace(tmp1)
var tmp2 = cl.getClass("index.base.net.ClassLoader");
trace(tmp2)
var tmp3 = cl.getClass("index.base.geom.Dot");
trace(tmp3)
}
/**
* trace的结果:
* [class ByteLoader]
* [class ClassLoader]
* [class Dot]
*/
我们的目的就达到了!
接下来是源代码!
package index.base.net{
import flash.display.Loader;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import flash.events.Event;
import flash.events.ProgressEvent;
import flash.events.EventDispatcher;
import flash.system.LoaderContext;
public class ClassLoader extends EventDispatcher{
public var url:http://webjx.com/flash/String;
public var loader:Loader;
//构造函数
public function ClassLoader(obj:Object = null,lc:LoaderContext = null) {
if(obj != null){
if(obj is ByteArray){
loadBytes(obj as ByteArray,lc);
}else if(obj is http://webjx.com/flash/String){
load(obj as http://webjx.com/flash/String,lc);
}else{
throw new Error("参数错误,构造函数第一参数只接受ByteArray或http://webjx.com/flash/String");
}
}
}
//加载
public function load(_url:http://webjx.com/flash/String,lc:LoaderContext = null):void{
url = _url;
loader = new Loader;
loader.load(new URLRequest(url),lc);
addEvent();
}
//加载字节
public function loadBytes(bytes:ByteArray,lc:LoaderContext = null):void{
loader = new Loader;
loader.loadBytes(bytes,lc);
addEvent();
}
//开始侦听
private function addEvent():void{
loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,progressFun);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE,completeFun);
}
//结束侦听
private function delEvent():void{
loader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS,progressFun);
loader.contentLoaderInfo.removeEventListener(Event.COMPLETE,completeFun);
}
//加载成功,发布成功事件
private function completeFun(e:Event):void {
delEvent();
dispatchEvent(e);
}
//加载过程
private function progressFun(e:ProgressEvent):void{
dispatchEvent(e);
}
//获取定义
public function getClass(className:http://webjx.com/flash/String):Object {
return loader.contentLoaderInfo.applicationDomain.getDefinition(className);
}
//是否含有该定义
public function hasClass(className:http://webjx.com/flash/String):Boolean {
return loader.contentLoaderInfo.applicationDomain.hasDefinition(className);
}
//清除
public function clear():void{
loader.unload();
loader = null;
}
}
}