AS3阵列按钮嵌套

时间:2012-04-11 15:48:37

标签: arrays actionscript-3 flash-cs5

我有一个按钮列表:

agreeButton disagreeButton container.clickButton1 container.clickButton2

Container是另一个movieclip,里面是最后两个按钮。

如何将它放在数组中并将所有相同的侦听器应用于每个数组?

var buttonArray:Array = new Array("agreeButton", "disagreeButton", "container.clickButton1", "container.clickButton2");
for (var i:int=0; i<buttonArray.length; i++) {
    this[buttonArray[i]].addEventListener(MouseEvent.ROLL_OVER, mouseRollOver);
    this[buttonArray[i]].addEventListener(MouseEvent.ROLL_OUT, mouseRollOut);
    this[buttonArray[i]].addEventListener(MouseEvent.CLICK, mouseClick);
}

2 个答案:

答案 0 :(得分:2)

保留对按钮的引用并将它们添加到数组中。

var agreeButton:Button = new Button();
var disagreeButton:Button = new Button();

//... Code that will add the above instantiated buttons to the canvas

var buttonArray:Array = new Array(agreeButton, disagreeButton);

for (var i:int = 0; i < buttonArray.length; i++) {    
buttonArray[i].addEventListener(MouseEvent.CLICK, mouseClick);
}


private function mouseClick(event:MouseEvent):void {
    Alert.show("Boom!");
}

答案 1 :(得分:1)

我会创建一个button类,由每个按钮扩展。在按钮类中添加eventListeners

示例:

请原谅我,如果这有问题,我还没有在AS3中编码一段时间。

class MyButton extends Button
{
    public function MyButton()
    {
        this.addEventListener(MouseEvent.ROLL_OVER, mouseRollOver);
        this.addEventListener(MouseEvent.ROLL_OUT, mouseRollOut);
        this.addEventListener(MouseEvent.CLICK, mouseClick);
    }
    //... Add mouseRollOver, mouseRollOut, mouseClick methods
}

你的个人按钮

class DisagreeButton extends MyButton
{
    public function DisagreeButton()
    {

    } 
}

class AgreeButton extends MyButton
{
    public function AgreeButton()
    {

    } 
}

实例化按钮后,所有事件侦听器都将应用于每个按钮。