Reputation: 531
I'm writing a inline function in AS3 as a Event handler for a Loader class, the issue I having is that in this inline function it needs to access variables outside the scope of the function.
Here's the code I running:
for(var i:uint=0;i<numChildren;i++){;
var displayObj:DisplayObject = getChildAt(i);
var displayObjWidth = displayObj.width;
if (elementname == displayObj.name)
{
var loader:Loader = new Loader();
var urlRequest:URLRequest = new URLRequest(loadURL);
loader.load( urlRequest );
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(e:Event){
var mw:Number = displayObj.width;
var mh:Number = displayObj.height;
var tempImage:Bitmap = new Bitmap(e.target.content.bitmapData);
image.bitmapData = tempImage.bitmapData;
image.width = mw;
image.height = mh;
loader.width = displayObj.width;
loader.height = displayObj.height;});
loader.x = displayObj.x;
loader.y = displayObj.y;
addChild( loader );
removeChild( displayObj );
}
This function is loading a image from a URL, then finding a match child element and replacing the existing image with the new one that has loaded.
The problem I'm having is getting is being able to access the height and width of the original display object I am replacing with the new one loaded via the Loader class.
How can I access these variables outside the scope of the function or pass them to the function?
Upvotes: 0
Views: 1735
Reputation: 90736
First of all, to save yourself some headaches, you should put the event handler in a separate, non-anonymous function, otherwise all sorts of scoping issues can happen.
Secondly, you can use a dictionary to create the image / display object relationship that you need. Basically, when you create the loader, you save it in the dictionary as the key, and the displayObj as the value.
Something like that should work:
private var imageToDisplayObj:Dictionary = new Dictionary();
function loader_complete(e:Event){
var displayObject:* = imageToDisplayObj[event.currentTarget];
// Do something with the display object
});
for(var i:uint=0;i<numChildren;i++){;
var displayObj:DisplayObject = getChildAt(i);
var displayObjWidth = displayObj.width;
if (elementname == displayObj.name)
{
var loader:Loader = new Loader();
var urlRequest:URLRequest = new URLRequest(loadURL);
loader.load( urlRequest );
// Map the loader to the display object
imageToDisplayObj[loader] = displayObj;
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loader_complete);
loader.x = displayObj.x;
loader.y = displayObj.y;
addChild( loader );
removeChild( displayObj );
}
Upvotes: 3