Skip to main content
Known Participant
May 13, 2014
Answered

Several buttons and dynamic(?) EventListener

  • May 13, 2014
  • 1 reply
  • 626 views

Hi everyone,

I place 10 buttons on my stage, name it "b1", "b2", "b3",.. , "b10".

All these buttons should use the same function.

Is it possible to do it dynamically?

var a: Array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

for (var i = 0; i < a.length; i++) {

button = "b" + a;

  this[button].addEventListener(MouseEvent.CLICK, onClick_b);

  function onClick_b(pEvt: Event): void {

  my_mc.play();

  }

}

Only the button "b10" plays the function.

Anyone an idea how to let all the other buttons play this function?

Thank you! C.

This topic has been closed for replies.
Correct answer moccamaximum

Hi mm, I tried this:

this[button].addEventListener(MouseEvent.CLICK, onClick_b);

and it works for the button "bthree".

But the other buttons won't work.


what you want is this:

for (var i = 0; i < a.length; i++) {

    getChildByName("b" + a).addEventListener(MouseEvent.CLICK, onClick_b);

     }

1 reply

Amy Blankenship
Legend
May 13, 2014

Assuming all your buttons are Button symbols, and hence are SimpleButtons and they all exist at the point you run this code:

var loops:numChildren;

for (var i:int=0; i<loops; i++) {

     var btn:SimpleButton = getChildAt(i) as SimpleButton;

     if (btn) {

          btn.buttonMode = true;

          btn.addEventListener(MouseEvent.CLICK, onButtonClick);

     }

}

//note the function is defined outside the for loop

function onButtonClick(e:Event):void {

     if (my_mc) {

          my_mc.play();

     }

}

chasblnAuthor
Known Participant
May 14, 2014

Thank you for your answers, this solution works, but I need an array in my project...

Now my buttons are called "bone", "btwo", "three".

var button: String;

button = "b";

var a: Array = ["one","two","three"];

for (var i = 0; i < a.length; i++) {

    button = "b" + a;

     button.addEventListener(MouseEvent.CLICK, onClick_b);

     }

function onClick_b(pEvt: Event): void {

    my_mc.play();

    }

But it doesn't work...

Inspiring
May 14, 2014

var button: String;

...

button.addEventListener(MouseEvent.CLICK, onClick_b);


You can`t add en eventlistener to a string