Skip to content

Instantly share code, notes, and snippets.

@jamesmorgan
Created February 9, 2012 19:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesmorgan/1782294 to your computer and use it in GitHub Desktop.
Save jamesmorgan/1782294 to your computer and use it in GitHub Desktop.
Loads a given image asset in ActionScript, setting the source on the given image
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));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment