Skip to main content
Known Participant
November 9, 2022
Question

How to optimize this in AS3

  • November 9, 2022
  • 1 reply
  • 128 views

Good afternoon!

I've been learning AS3 for a couple of small projects I've been working on.

Could use some help with two "quick" questions:

 

1st-

How can I assign EventListeners to several buttons at once?
Example:

I have several buttons (called bt_01, bt_02, and so on)... Instead of writing 20 lines of code for the 20 buttons telling them which function to call, can I do this recursively once?

 

2nd-

How can I assign a function, depending on the name of the button itself?

Example:

If a button is called bt_01, I want it to call function_01

If it's called bt_02, then I want it to call function_02

And so on...

 

I'm sure this is basic programing for most, but I'm kinda confused on how to apply it.

    This topic has been closed for replies.

    1 reply

    kglad
    Community Expert
    Community Expert
    November 9, 2022

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

    this["bt"+padF(i)].addEventListener("MouseEvent.CLICK,f);

    }

    function f(e:MouseEvent):void{

    var s:String = e.currentTarget.name.split("bt_")[1];

    this["f_"+s]();

    }

     

    function padF(n:int):int{

    if(n<10){

    return +"0"+n; 

    } else {

    return n;

    }

    }