0

I'm using an HTTP request to download a image in binary format. When the downloading is complete, I want to process it, but I also want to pass the image's ID to the complete handler function... how is this done?

var loader:URLLoader = new URLLoader();

for(var i:int = 0 ; i<5; i++){

    /* When completed I want to access the variable "i" */
    loader.addEventListener(Event.complete, completeHandler);
    loader.load(/* a url request */);
}

private function completeHandler(event:Event):void
{
     /* I want to access the passed parameter "i" so 
      it is the same as it was when the eventListener was added, 0,1,2,3 or 4 */

 }

Is this possible? Ive tried extending Event, but I want to handle a COMPLETE event

Thanks Phil

p_mcp
  • 2,643
  • 8
  • 36
  • 75

2 Answers2

4

This should be possible using Flex's dynamic function construction. A similar question was asked here and here.

Here's an example:

The parameters and handler:

var parameters:String = "Some parameter I want to pass";

private function loadLocalData(e:Event, parameter:String):void
{
  // voila, here's your parameter
}

private function addArguments(method:Function, additionalArguments:Array):Function 
{
  return function(event:Event):void {method.apply(null, [event].concat(additionalArguments));}
}

Usage in your example:

for(var i:int = 0 ; i<5; i++){

    /* When completed I want to access the variable "i" */
    loader.addEventListener(Event.complete, addArguments(completeHandler, [i]));
    loader.load(/* a url request */);
}

private function completeHandler(event:Event, id:int):void
{
     /* I want to access the passed parameter "i" so 
      it is the same as it was when the eventListener was added, 0,1,2,3 or 4 */

}
Community
  • 1
  • 1
Jason Towne
  • 8,014
  • 5
  • 54
  • 69
  • Thanks! So when im inside completeHandler(e:Event), how do I access "i"? – p_mcp Apr 04 '11 at 15:17
  • @Phil, `i` would get passed as the `id` parameter in the `completeHandler` function. You can access it using `id`. Of course, you could change `id` to `i` if you prefer. :) – Jason Towne Apr 04 '11 at 15:24
0

exacly - additional method addArguments(...) is best solution, im using this same but it calle passParameters

public function passParameters(method:Function,additionalArguments:Array):Function
{return function(event:Event):void{
    method.apply(null, [event].concat(additionalArguments));}
}

explanation of this is here - its simple and always work http://sinfinity.pl/blog/2012/03/28/adding-parameters-to-event-listener-in-flex-air-as3/

mihau
  • 247
  • 3
  • 9