wzazza
wzazza

Reputation: 853

Flash ActionScript2 loop

I have 180 buttons in one Flash file and for all buttons I need a roll over and a click event, so the code I`m using is:

button1.onRollOver = function() { //on roll over change button color as white
  var color = new Color(button1); 
  color.setRGB("0xFFFFFF"); 
};
button1.onRollOut = function() { //on roll out reset button color to it`s default
  resetColorFunction(); 
};
button1.onPress = function() { //on click/press runs javascript function in page
  getURL("javascript:ButtonPress('button1');"); 
};

The problem is that I have 180 buttons, so I`m copying this code to each button, button1, button2, button3, button4 ...etc until button180.

Is there any way to loop through all buttons with one simple code, function.

Thank you

Upvotes: 1

Views: 1664

Answers (3)

Bishop
Bishop

Reputation: 91

You can use a for-in loop in the stage or any container.

for (var item in this) {
    if (this[item] instanceof Button) { //-- Use the most relevent class for abstraction
        var btn = this[item];
        trace ("Button: " + btn._name + " btn._x:" + btn._x + " a: " + btn._alpha);

        //-- add Logic for event handlers.
    }
}

Upvotes: 1

Dave Hart
Dave Hart

Reputation: 347

You can use eval in Actionscript 2 to get all your buttons tagged with minimal effort.

buttonRollOver = function() { ... };
buttonRollOut = function() { ... };
buttonPressed = function() { ... };

for (var i=1; i<181; i++)
{
   eval("button"+i).onRollOver = buttonRollOver;
   eval("button"+i).onRollOut = buttonRollOut;
   eval("button"+i).onPress = buttonPressed;
}

And there you have it all nice and fast.

Upvotes: 0

Tomislav Dyulgerov
Tomislav Dyulgerov

Reputation: 1026

You can add all of these buttons to a collection of some sort, then loop through all of the elements and add the event handlers. Something like this:

var buttons:ArrayCollection = new ArrayCollection();
var button1:Button = new Button();
var button2:Button = new Button();
// some more buttons creation ...

and each time you create a button, you simply add it to the buttons collection.

buttons.addItem(button1);
buttons.addItem(button2);
// etc

Finaly you just loop through all the buttons and add the required event handlers.

for each (var button:Button in buttons)
{
    button.onRollOver = function() { // handle RollOver };
    button.onRollOut  = function() { // handle RollOut };
    button.onClick    = function() { // handle Click };
}

To use an array you can do the following:

var buttons:Array = [];
buttons.push(button1);
// add all other buttons..

for (var i:uint = 0; i < buttons.length; i++)
{
    var button:Button = Button(buttons[i]);
    button.onRollOver = function() { // handle RollOver };
    button.onRollOut  = function() { // handle RollOut };
    button.onClick    = function() { // handle Click };
}

Upvotes: 0

Related Questions