views:

175

answers:

2

I have the following code in ActionScript3 for loading images:

// Create the image areas
    var imageArea1 = new imageArea();
    var imageArea2 = new imageArea();
    var imageArea3 = new imageArea();
    var imageArea4 = new imageArea();
    var imageArea5 = new imageArea();

    var image1;
    var image2; 
    var image3; 
    var image4; 
    var image5;

    addChild(imageArea1);
    addChild(imageArea2);
    addChild(imageArea3);
    addChild(imageArea4);
    addChild(imageArea5);

    // Image1
    // function to load images to the page
    function loadImage1(url:String):void {
     image1 = new Loader();
     image1.load(new URLRequest(url));
     image1.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded1); 
    }

    //Callback event after image has been loaded.
    function imageLoaded1(e:Event):void { 
     // Load Image 
     imageArea1.addChild(image1);//display the photo
     //trace ('width:'+image1.width,' height:'+image1.height);
     image1.y = (stageHeight-image1.height);
     //trace(image1.y);
     var otherindex = getChildIndex(myBackground)
     setChildIndex(imageArea1,otherindex + 1);
    }

From the looks of it, I would have to copy and paste loadImage1 and imageLoaded1 functions for each image. I would ideally like to somehow pass in params to the .addEventListener function.

How can I refactor this so that I don't have to copy and paste the functions for each image, it seems repetitive.

A: 

I think the easiest way will be to add the imageX as a parameter:

function loadImage(url:String, imageObj:Object):void {
    imageObj = new Loader();
    imageObj.load(new URLRequest(url));
    imageObj.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded1); 
}

Will that be good for you? I hope it will :)

yn2
A: 

Try this (I haven't tested it, but it should work if you can get it to compile -- don't forget the proper imports ;-) ):

var imageURLs:Array = ['blah.png', 'blah2.png', 'foo.png'];
var imageLoaders:Array = new Array();
var imageAreas:Array = new Array();

for each (var url:String in imageURLs) {
 var loader:Loader = new Loader();
 loader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded);
 loader.load(new URLRequest(url));

 imageLoaders.push(loader);

 var theImageArea:imageArea = new imageArea();
 addChild(theImageArea);
 imageAreas.push(theImageArea);
}

function imageLoaded(e:Event):void
{
 var loader:Loader = Loader(e.target.loader);

 var index:int = imageLoaders.indexOf(loader);
 imageAreas[index].addChild(loader);

 loader.y = (stageHeight - loader.height);

 var otherChildIndex:int = getChildIndex(myBackground);
 setChildIndex(imageAreas[index], otherChildIndex + 1);
}
Cameron