Search code examples
xmlactionscript-3loader

AS3: Messed up order of loading from an XML list


So I'm trying to load up a group of thumbnails like the many times before, but this time their order of showing up is completely messed up, I can't find out WHY!!

function thumbsLoader(): void {
    for (var i: uint = 0; i < VideosTotal; i++) {
        thumbURL = VideoList[i].@THUMB_URL;
        thumbLoader = new Loader();
        thumbLoader.load(new URLRequest(thumbURL));
        thumbLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, viewThumbs);
        thumbLoader.name = i.toString();
    }
}

function viewThumbs(e: Event): void {
    thumb = e.target.loader;
    trace(thumb.name);
}

The trace function outputs : 13 11 6 20 18 4 14 16 7 17 2 1 15 9 0 8 22 3 12 10 5 19 21

instead of in increasing order... what can be wrong ?? Thanks a lot.


Solution

  • Loading file with Loader is performing asynchronously. Generally, it doesn't a problem and no need to fix it. But if you must have strict order of loading you can build a chain of Loaders. It may looks like this:

    private var thumbIndex:uint = 0;
    
    private function loadImage(index:uint):void
    {
        thumbURL = VideoList[index].@THUMB_URL;
        thumbLoader = new Loader();
        thumbLoader.load(new URLRequest(thumbURL));
        thumbLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, viewThumbs);
        thumbLoader.name = i.toString();
    }
    
    private function viewThumbs(e:Event):void 
    {
        thumb = e.target.loader;
        trace(thumb.name);
        if (thumbIndex < VideoList.length()) {
            thumbIndex++;
            loadImage(thumbIndex);
        }
    }
    

    This code makes your loading synchronously.

    Another way: load images as it loaded and sort after loading.

    You may add loaded thumb into Array like

    array.push({id: thumb.name, thumb: thumb.content});
    

    When all images will be loaded you need to call

    array.sortOn("id");
    

    And you will have sorted array of images. Then you can add them to stage. But in this solution you will require some counter anyway to detect when loading ends.