Yan
Yan

Reputation: 1444

passing parameters to addEventListener AS3

I am struggling passing paramters to function on onComplete event handler.

It seems that my problem is with the event.Complete code..

I just want to load image from a url and transfer parameter.

This is my code:

var imageURLRequest:URLRequest = new URLRequest(pic); 
var myImageLoader:Loader = new Loader(); 
myImageLoader.load(imageURLRequest); 

myImageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,function(evt:Event.COMPLETE){
    doIt(evt, "Shift key was down:")
},false,0, true);

function doIt(evt:Event, msg:String) {
    var myBitmapData:BitmapData = new BitmapData(myImageLoader.width, myImageLoader.height); 
    myBitmapData.draw(myImageLoader); 
    var myBitmap:Bitmap = new Bitmap; 
    myBitmap.bitmapData = myBitmapData; 
}

Thank you very much.

Upvotes: 2

Views: 4590

Answers (3)

user1837285
user1837285

Reputation:

Firstly, as Gio said, remove that .COMPLETE from evt:Event.COMPLETE because it's returning a String instead of the Event the function needs.

Then, instead of setting that last fearsomely unpredictable parameter (useWeakReference) to true in your addEventListener(), I recommend you keep the reference in a variable to use removeEventListener() on it at the right time. A way to do this (while answering your question) is:

var imageURLRequest:URLRequest = new URLRequest(pic);
var myImageLoader:Loader = new Loader();
myImageLoader.load(imageURLRequest);

var functionDoIt:Function = doIt("Shift key was down:");
myImageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, functionDoIt);

function doIt(msg:String):Function {
  return function(evt:Event):void {
    // Now you can use both "msg" and "evt" here
    var myBitmapData:BitmapData = new BitmapData(myImageLoader.width, myImageLoader.height);
    myBitmapData.draw(myImageLoader);
    var myBitmap:Bitmap = new Bitmap(myBitmapData);
  }
}

// Remove the listener when you don't need it anymore:
//myImageLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE, functionDoIt);

You can understand this solution better by reading this answer.

Upvotes: 1

Gio
Gio

Reputation: 1954

Remove .COMPLETE from the handler inner function so that your listener looks like this:

myImageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(evt:Event)
{
   doIt(evt, "Shift key was down:")
} , false, 0, true);

Upvotes: 2

Jevgenij Dmitrijev
Jevgenij Dmitrijev

Reputation: 2238

Look at the Loader class as loader, not as DisplayObject even when it is:

var myBitmap:Bitmap;
var contentLoader:Loader = new Loader();
contentLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, handleComplete);
contentLoader.load(imageURLRequest); 

function handleComplete(e:Event):void
{
    myBitmap = contentLoader.content as Bitmap;
}

Upvotes: 2

Related Questions