Thursday, 9 February 2012

Dynamically Loading Assets in AS3

Recently I have had the requirement to to load assets from a given location inside one of our flex application. It took my a good few hours to work how and or the best way to go around this is so in the hope that this will save someone, somewhere sometime here is the code. Basically it loads a given image resource, showing or hiding the image depending on the outcome of the load.

Asset Loader:
public class DynamicAssetsLoader {
public static function loadImage(image:Image, assetUri:String):void
{
// if not
if(!assetUri){
image.includeInLayout = false;
image.visible = false;
image.source = null;
return;
}
// Be safe here at all times
try {
var pictLdr:Loader = new Loader();
var pictURLReq:URLRequest = new URLRequest(assetUri);
pictLdr.load(pictURLReq);
// Handle calback from completed event in roder to set image source and display asset
pictLdr.contentLoaderInfo.addEventListener(Event.COMPLETE, function(event:Event):void {
if(null == pictLdr || null == pictLdr.content){
image.source = null;
image.includeInLayout = false;
image.visible = false;
}
else{
image.includeInLayout = true;
image.source = pictLdr.content.parent;
image.visible = true;
}
});
// Set IO handler to gracefully handle loading issues
pictLdr.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, function(e:IOErrorEvent):void {
onError(image, assetUri);
});
}
// Catch the unknown an dlog error
catch(e:Error){
onError(image, assetUri);
}
}
// On all errors, hide image and log unknown error
private static function onError(image:Image, assetUri:String):void
{
image.includeInLayout = false;
image.visible = false;
image.source = null;
ErrorThrower.throwError(new Error("Error thrown when attempting to load asset, asset="+assetUri, CustomError.UNKNOWN_ASSET_URI));
}
}


This simple snippet may hopefully save you some time.