AS3:向人口循环添加功能

AS3: Adding function to population loop

基本上我有 2 个带有一些代码的动画片段对象,目前只是为了跟踪它们。单击时蓝色圆圈将显示 'Blue',单击时红色圆圈将显示 'Red'。这在理论上工作得很好,直到我添加了一个人口循环,这增加了更多。然后每种颜色只有 1 个正确,其余的只是 'mock' 个圆圈。我希望每个圆圈都能告诉我它们的颜色。

这是我的 .fla 代码:

import flash.events.MouseEvent;
BlueBall.addEventListener(MouseEvent.CLICK, fun1)

function fun1(e:MouseEvent){
    trace("Blue!");
}
RedBall.addEventListener(MouseEvent.CLICK, fun2)

function fun2(e:MouseEvent){
    trace("Red!");
}

这是 .as 文件中的填充循环:

private function PopulateCircles():void
{
    for (var i:int=0; i < 10; i++)
    {
        var blueCircle:BlueCircle = new BlueCircle();
        this.addChild(blueCircle);

        var redCircle:RedCircle = new RedCircle();
        this.addChild(redCircle);
    }
}

tldr;如何让点击事件发生在每个新填充的圈子上?

其实很简单。正如您订阅方法来监听预先设计的实例的事件一样,您可以通过临时变量引用进行订阅。只要变量持有引用(或 C++ 术语中的指针),您就可以对实例进行寻址并对预先设计的 MovieClip:

执行任何操作
private function PopulateCircles():void
{
    var aRed:RedCircle;
    var aBlu:BlueCircle;

    for (var i:int = 0; i < 10; i++)
    {
        // If there are no mandatory constructor arguments,
        // you can omit the () brackets.
        aRed = new RedCircle;
        aBlu = new BlueCircle;

        // Disperse clips to random places.
        aBlu.x = 500 * Math.random();
        aBlu.y = 500 * Math.random();
        aRed.x = 500 * Math.random();
        aRed.y = 500 * Math.random();

        // Subscribe methods to newly created instances.
        aRed.addEventListener(MouseEvent.CLICK, fun2);
        aBlu.addEventListener(MouseEvent.CLICK, fun1);

        // You're operating inside 'this' object,
        // no need to explicitly point it out.
        addChild(aRed);
        addChild(aBlu);
    }
}