Switch Statement in ActionScript 3

2011.03.03

Using switch or case statements in place of “if” statements isn’t hard once you understand how the case is determined. Most examples on the web will show you how to write the switch statement but not how to call it.

The switch statement goes inside a function. In this case the function is named “updateText”. Now imagine you have several buttons in your movie. When the user clicks on any of those buttons, that button is the “event.target”

In plain english it goes like this:
If the “event.target” clicked is “button1_btn” then display “case 1″ in the “tBox_txt” text box then “break”.

What’s up with the Break?
This one is real simple. The “break” is required. Without it, every case will be evaluated and result in a fail.

In this example “event.target” is being evaluated.

button1_btn.addEventListener(MouseEvent.CLICK, updateText)
//
function updateText(event:MouseEvent):void {
switch (event.target) {
case “button1_btn” :
tBox_txt.text = “case 1″;
break;
case “button2_btn” :
tBox_txt.text = “case 2″;
break;
case “button3_btn” :
tBox_txt.text = “case 3″;
break;
}
}

Categories : Flash  ActionScript 3.0