我一直在嘗試通過創建一個新的ApplicationDomain並將其傳遞給加載器的上下文來動態加載庫。我做錯了什麼是存儲對該ApplicationDomain的引用,並嘗試從該引用獲取定義。由於某些原因返回null。通過實現paleozogt的答案並修改了動態加載swf的結果,我最終得到了正確的代碼,該代碼不使用ApplicationDomain的存儲引用,而是從加載器的contentLoaderInfo中獲取它。
下面的代碼,如果你想動態加載庫:
package
{
import flash.display.Loader;
import flash.events.Event;
import flash.net.URLRequest;
import flash.system.ApplicationDomain;
import flash.system.LoaderContext;
public class AlchemyDynamicLoad
{
private var _library:Object;
private var _loader:Loader;
public function AlchemyDynamicLoad()
{
var loaderContext:LoaderContext = new LoaderContext(false, new ApplicationDomain());
var request:URLRequest = new URLRequest("../assets/mylib.swf");
_loader = new Loader();
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
_loader.load(request, loaderContext);
}
private function completeHandler(event:Event):void
{
// NOTE: Storing a reference to the application domain you feed to the loaderContext and then trying to get the
// definition from that reference is not going to work for some reason. You have to get the applicationDomain
// from the contentLoaderInfo, otherwise getDefinition returns null.
var libClass:Class = Class(_loader.contentLoaderInfo.applicationDomain.getDefinition("cmodule.mylib.CLibInit"));
_library = new libClass().init();
}
}
}
而這裏的代碼,如果你想將它嵌入(paleozogt的答案):
package
{
import flash.display.Loader;
import flash.events.Event;
public class AlchemyStaticLoad
{
[Embed(source="../assets/mylib.swf", mimeType="application/octet-stream")]
private static var _libraryClass:Class;
private var _library:Object;
private var _loader:Loader;
public function AlchemyStaticLoad()
{
_loader = new Loader();
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
_loader.loadBytes(new _libraryClass());
}
private function completeHandler(event:Event):void
{
var libClass:Class = Class(_loader.contentLoaderInfo.applicationDomain.getDefinition("cmodule.mylib.CLibInit"));
_library = new libClass().init();
}
}
}
謝謝,送我正確的方向。 –