ActionScript 3重构图像加载器

时间:2009-09-28 19:57:27

标签: flash actionscript-3

我在ActionScript3中有以下代码用于加载图像:

// 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函数。

如何重构这一点,以便我不必复制和粘贴每个图像的功能,这似乎是重复的。

2 个答案:

答案 0 :(得分:0)

我认为最简单的方法是将imageX添加为参数:

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

这对你有好处吗?我希望它会:)

答案 1 :(得分: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);
}