views:

51

answers:

4

I'm using Loader to get the image data out of a ByteArray. The problem is that I need to store that image data with a name (which is known beforehand) once it's passed to the complete handler. Since the operation is asynchronous, I can't be sure which image of multiple will finish loading first, so it seems I need to pass the information with it somehow... I can't seem to find any properties of Loader that pass any vaguely useful information along.

Any recommendations on how I might accomplish this?

+1  A: 

Couldn't you just use the Loader.name property?

var ldr:Loader = new Loader();
ldr.name = 'name_of_the_loader';
ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderListener);
ldr.loadBytes(aByteArray);

...

function loaderListener(event:Event):void {
  trace('name of the completed loader is '+LoaderInfo(event.target).loader.name);
}

Could you provide some code?

kkyy
Yeah, this does work. I was having trouble with this yesterday, so thanks for clearing that up. Marking this as the best solution for now as it requires the least code. Thanks.
grey
A: 

loader.contentLoaderInfo.url will be having URL of the loaded image (e.g http://sometURL/image1.jpg).

bhups
Not if the image data comes from a bytearray, as the op states.
kkyy
As cited, it doesn't work in this instance, and the URL property is read only.
grey
A: 
private var loaders:Array = [];
private var names:Array = [];

    //inside loadImages method
    for(i = 0; i < len; i++)
    {
        var ldr:Loader = new Loader();
        //add listeners and call load
        loaders.push(ldr)
        names.push(name-of-ith-image);
    }

private function onLoadComplete(e:Event):void
{
    var index:Number = loaders.indexOf(LoaderInfo(e.target).loader);
    var requiredName:String = names[index];
    trace(requiredName);
}
Amarghosh
That should work too.
grey
A: 

First solution would be to use a Dictionary to map the Loader instances to names. Like this:

private var names : Dictionary = new Dictionary();
...

var ldr : Loader = new Loader();
names [ ldr ] = 'someName';
ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderListener);
ldr.loadBytes(aByteArray);

...

function loaderListener(event:Event):void {
  trace('name of the completed loader is '+ names[ event.target ] );
}

The other solution would be to use a functor, like this:

var ldr : Loader = new Loader();
ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, createListener( 'someName' ) );
ldr.loadBytes(aByteArray);

...

function createListener( imgName : String ) : Function {
    return function ( event : Event ) : void {
      trace('name of the completed loader is '+ imgName );
    }
}
Creynders
Clever solutions, thanks.
grey