Search code examples
loopsactionscript-3eventsflashloader

Flash AS 3 Loader OnComplete Inside a Loop


As a followup to the question, How to get associated URLRequest from Event.COMPLETE fired by URLLoader, how can I make the function work for loader object in a loop?

Here is my existing (rough) code; I always get the mylabel from the last element of the array.

var _loader = new Loader(); 
for (j = 0; j < 5; j++) {
    //mylabel variable is correct setup in the loop
    _loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(e:Event):void {
        doneLoad(e, mylabel);
    });

    _loader.load(new URLRequest(encodeURI(recAC[j].url)));

}//for loop

Solution

  • As per the comments above, this won't work because:

    1) You're just adding the same event listener 5 times to the loader. 2) You're just reseting your same loader object 5 times.

    The final output will just be as though you only called it the last time.

    There are a variety of ways to address this - loading stuff asynchronously is one of the great mindfucks of learning to code - but the simplest way is probably just to create five separate loaders.

    I'd do something like this:

    var loaders:Array = [];
    var labels:Array = ["label1", "label2", "label3", "label4", "label5"];
    for (var j:int = 0; j < 5; j++) {
    loaders[j] = new Loader();
    loaders[j].contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
    loaders[j].load(new URLRequest(encodeURI(recAC[j].url)));
    }
    
    function completeHandler(e:Event):void {
    doneLoad(e.currentTarget, labels[loaders.indexOf(e.currentTarget)]);
    }
    

    The confusing part is finding a good way to keep track of which load is associated with which label etc, since in theory your loads can finish in any order. That's why I've got a separate label array there, and then you just match up the desired label with the loader that just finished loading.

    I hope that helps!