Question

I still can't understand how some easy things turns harder in AS3. Here, I would like to load a Bitmap in a function, and, on Complete, return its value to let the app continue. Something like that would be easy to use :

var imageLoader:Bitmap;

for (var i:int=0; i<n.length; i++) {
    imageLoader = loadFile(name[i]);
    trace(imageLoader); // [object Bitmap]
}

function loadFile(name:String):Bitmap {
   imgLoad:ImageLoader = new ImageLoader(url + name)
   imgLoad.addEventListener(LoaderEvent.COMPLETE, fileLoaded);
   imgLoad.load;

   function fileLoaded(ev:LoaderEvent) {
      return ev.target.content; // the file now loaded is a bitmap.
   }
}

But it doesn't work. The return value must be at the end of loadFile(). I don't really understand what should I do to get my code optimized and working. The first time I tried I used something like a "loopingLoad" method with a "_Count:int" and "_CountEnd" to know when to stop calling loadFile... Well, it was working nice but it was really ugly. So, I would like to know how to simply load several files with a "For".

Thanks for your help.

Was it helpful?

Solution

You basically want synchronous loading. No, you can't do directly this, you have to perform a workaround method to provide a loaded bitmap to elsewhere. This, though, will make you rethink the entirety of your application logic, at least the part where you want your images loaded.

In order to load several files with a for loop, you need to do the following: First, you make an array of your Loaders, each with an attached Event.COMPLETE listener. Second, your application should be notified when one of the loaders will complete, providing either an index, or a content link, or both.

var loaders:Array=new Array();
...
for (var i:int=0;i<urlArray.length;i++) {
    // urlArray is the array with links to bitmaps
    var l:Loader=new Loader();
    l.addEventListener(Event.COMPLETE,onComplete);
    l.load(new URLRequest(urlArray[i]));
    loaders.push(l); // store it, if you want
    // do other stuff, like preparing to accept an image
} // and that's all, you initiate and wait!
...
function onComplete(event:Event):void {
    var i:int=loaders.indexOf(event.target); // get the index
    event.target.removeEventListener(Event.COMPLETE,onComplete);
    if (i<0) return; // oops! 
    notifyApplication(event.target.content); // now you transfer a ready bitmap
    // add "i" if you need that index of your former "for" loop here
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top