Multible targets - easy one!

I have 4 buttons with instance names: ‘alfa’, ‘bravo’, ‘charlie’ and ‘delta’.
I want to make a function that runs on mouse click on either of the buttons.
I tried this, but could remember exactly how it should look:

[alfa,bravo,charlie,delta].onPress = function () {
    trace ("onPress called");
};

seems like you need a function:

function press_button() {
	trace ("onPress called")
}
alpha.onPress = press_button;
bravo.onPress = press_button;
charlie.onPress = press_button;
delta.onPress = press_button;

I personally don’t know that particular syntax you’re refering to, but a much more n00bish way to do it would be:

alfa.onPress = bravo.onPress = charlie.onPress = delta.onPress = function(){
trace(‘onPress called’);
}

FYI, I believe it’s “alpha”, not alfa.

Roger that!

if you think the amount of buttons might change the easiest way to handle it is an array. Something like

//this assumes the objects are all on the same timeline as the code
//if not you'll have to include the path to the button in the array
myArray = [alpha, bravo, charlie, delta]
for(i=0; i<myArray.length; i++){
   myArray*.onPress = function{
   //function code here
   }
}

This is useful because all you have to do is add more button instance names to the array and don’t have to repeat the code each time.

:hr:

lol… this went from a “simple function question” to “looping though an array with dynamic variables” pretty quick:lol:

Your everywhere Defective! I can’t get rid of you!!! :slight_smile:

I would only go the array route if you are absolutely positive that you will be adding and removing buttons dynamically… There’s no need for the extra work required to create the array, populate, then iterate over… the assignment to each one is your most efficient bet. I’m only saying this if you are NOT going to be changing the buttons dynamically… if you are, luna’s way is going to be the way to go.

TakeCare

_Michael

:hugegrin:

Well, it’s not too far a cry from the code hommer posted in the first post.

hehe :wink:

I think that was an ‘ouch’! But your code is nice Luna. I think it’s better to make an array if you have a lot of buttons.

hey, sorry, wasn’t intended as an ouch at all! I think you were on the right track and since you had started using an array I thought I would just go with it. MichaelxxOA makes a good point though - no poing building a complex array if you only have 3 or 4 simple buttons that do the same thing. You can use Defective or FizixMan’s solution just as easily.

:hr:

Yeah, I used FizixMan’s solution.

alfa.onPress = bravo.onPress = charlie.onPress = delta.onPress = function(){
trace('onPress called');
}

I don’t know why he calls it n00bish though. It seems to be the shortest method.