Search code examples
actionscript-3flash

AS3 Event.COMPLETE passing argument


I am trying to pass an argument on Event.Complete, so once they load the image, i can handle them accordingly of the position, store them, etc. See below the code and the output:

var pic:Array = ["https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png","https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png","https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png","https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"];

for (var ii: uint = 0; ii < pic.length; ii++) {

var imageURLRequest:URLRequest = new URLRequest(pic[ii]); 
var myImageLoader:Loader = new Loader(); 
myImageLoader.load(imageURLRequest); 
trace ("the ii: " + ii);

myImageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(evt:Event)
{
   doIt(evt, ii)
} , false, 0, true);

function doIt(evt:Event, msg:int) {
    //var myBitmapData:BitmapData = new BitmapData(myImageLoader.width, myImageLoader.height); 
    //myBitmapData.draw(myImageLoader); 
    //var myBitmap:Bitmap = new Bitmap; 
    //myBitmap.bitmapData = myBitmapData; 
    trace ("message : " + msg);
}
}

/////Output
the ii: 0
the ii: 1
the ii: 2
the ii: 3

message : 4
message : 4
message : 4
message : 4

///Expected Output

/////Output
the ii: 0
the ii: 1
the ii: 2
the ii: 3

message : 0 
message : 1
message : 2
message : 3

Thank for the help Speego


Solution

  • As you might know, the Loader class inherits from DisplayObject which in turn means you have access to the .name property.

    Having this in mind you can 'abuse' this property to store the value of your ii variable as a string and send it to the doIt() function as the second parameter - after casting it back to an integer.

    So simply change this:

    var myImageLoader:Loader = new Loader(); 
    

    to this:

    var myImageLoader:Loader = new Loader(); 
    myImageLoader.name = ii.toString();
    

    and the onComplete callback handler to this:

    myImageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(evt:Event):void
    {
    doIt(evt, int(flash.display.LoaderInfo(evt.target).loader.name));
    }, false, 0, true);
    

    This should give you an output like this:

    the ii: 0
    the ii: 1
    the ii: 2
    the ii: 3
    message : 1
    message : 0
    message : 3
    message : 2