1

I have a list of buttons:

agreeButton disagreeButton container.clickButton1 container.clickButton2

Container is another movieclip and inside of it are the last 2 buttons.

How can I put it in array and have all the same listeners applied to each of them?

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 Answers 2

2

Keep a reference to the buttons and add them to an array.

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!");
}
Sign up to request clarification or add additional context in comments.

3 Comments

Just a quick question, what about the "container.clickButton1", "container.clickButton2" buttons? They are in a movieclip named "container". How do you declare the variable in a movieclip?
Also I used SimpleButton instead.
It doesn't matter where the buttons are as long as you have a reference to them from the code. Declare the buttons, add the event listeners and then add them to the container. Got it? :)
1

I would make a button class that is extended by each of these buttons. In the button class you add eventListeners.

Example:

forgive me if there are things wrong with this, I haven't coded in AS3 for a while.

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
}

Your Individual Buttons

class DisagreeButton extends MyButton
{
    public function DisagreeButton()
    {

    } 
}

class AgreeButton extends MyButton
{
    public function AgreeButton()
    {

    } 
}

Once you instantiate the buttons all the event listeners will be applied to each.

2 Comments

Can you give an example please?
@Anderson I added a rough example of what I was referring to

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.