Reputation: 11
I have various colour buttons that change the colour of a movieclip on click but I want to write code that says like if btnRed has been clicked, apply red ColorTransform
. This is because I have multiple buttons and I don't want to have to write methods that are almost identical just with different RGB multiplier values. Is there a way of doing it so that the event listener for each button calls the same method but then within that method it basically says if redBtn is clicked, change color to red
, if blueBtn is clicked, change color to blue
etc.
Upvotes: 0
Views: 107
Reputation: 13235
As M4tchB0X3r indicated, use a Dictionary
to store a lookup of button object to color transform. Here is working code, assuming your button names are btnRed
, btnGreen
, and btnBlue
, and that you have some kind of named object on the stage called box1
.
They key points here are that the Dictionary
can use object references as keys (not just integers and strings as with the simple Object
type), and that the target
property of an Event
object holds a reference to the thing that raised the event--in this case a button. In fact it's probably safer to use currentTarget
, because sometimes target
is a parent or child display object, due to the way events can bubble up and down the tree.
import flash.utils.Dictionary;
import flash.geom.ColorTransform;
var buttonToTransform:Dictionary = new Dictionary();
buttonToTransform[btnRed] = new ColorTransform(1.0, 0.2, 0.2);
buttonToTransform[btnGreen] = new ColorTransform(0.2, 1.0, 0.2);
buttonToTransform[btnBlue] = new ColorTransform(0.2, 0.2, 1.0);
// Note: for..in iterates over the keys of an object
// (vs. for each, which iterates over the values)
for(var btn:* in buttonToTransform) {
btn.addEventListener(MouseEvent.CLICK, onTransform);
}
function onTransform(e:MouseEvent):void {
this.box1.transform.colorTransform = buttonToTransform[e.currentTarget];
}
Upvotes: 2
Reputation: 1531
Hold all your Buttons in an Array, in the CLICK
Event determin which one was pressed with buttonArray.indexOf(event.target);
then get the according color value from a map
like a Dictionary
or an Object
.
You could also keep your Buttons in the Dictionary itself and loop through it to find your color.
Upvotes: 0