2009-09-28 64 views
0

我在ActionScript3的加載圖像下面的代碼:ActionScript 3的重構圖像裝載機

// 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); 
    } 

從外觀上來看,我將不得不爲每個圖像複製和粘貼loadImage1和imageLoaded1功能。我最好喜歡以params傳遞給.addEventListener函數。

我該如何重構這個,以便我不必複製和粘貼每個圖像的功能,它似乎是重複的。

回答

0

我認爲最簡單的方法將是在IMAGEX添加爲參數:

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

這將是對你有好處?我希望這將:)

0

試試這個(我沒有測試它,但它應該工作,如果你能得到它的編譯 - 不要忘了適當的進口;-)):

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); 
}