Skip to main content
Participant
January 25, 2014
Answered

dynamically create and addEventListener on mouse click

  • January 25, 2014
  • 1 reply
  • 453 views

Hi, I have 9 buttons on the main stage and each has an incremented instance name P0001, P0002, P0003...

I am trying to dynamically create and addEventListener on mouse click for each one then call the appropiate function when the button is clicked, this is what i have which doesnt work, am i going about this the wrong way? Thanks

for(var i:int = 1; i<10; i++) {

var btn1:String="P000"+i.toString();

var btn11:Object = btn1;

var ClickBtn:String="Func"+i.toString();

  btn11.addEventListener(MouseEvent.CLICK, ClickBtn);

   i=i+1;

}

function ClickBtn1(event:MouseEvent):void

{

trace("made it1");

}

function ClickBtn2(event:MouseEvent):void

{

trace("made it2");

}

......

This topic has been closed for replies.
Correct answer Ned Murphy

Use:

for(var i:int=1; i<10; i++) {

  this["P000"+String(i)].addEventListener(MouseEvent.CLICK, this["ClickBtn"+String(i)]);

}

1 reply

Ned Murphy
Ned MurphyCorrect answer
Legend
January 25, 2014

Use:

for(var i:int=1; i<10; i++) {

  this["P000"+String(i)].addEventListener(MouseEvent.CLICK, this["ClickBtn"+String(i)]);

}

DraydonAuthor
Participant
January 25, 2014

Cheers!