Thursday, June 17, 2010

Switch Case = Advance If else

If you haven't used Switch conditional statement then you are punishing yourself. By using switch statement you can reduce the code by 60% and is lot easier to read and understand.

Here is a little code for linking multiple websites to multiple button by calling a function. Now isn't that a awesome, one function handeling all MouseEvents


a_btn.addEventListener(MouseEvent.CLICK, openURL);
b_btn.addEventListener(MouseEvent.CLICK, openURL);
c_btn.addEventListener(MouseEvent.CLICK, openURL);

function openURL(e:MouseEvent):void
{
var url:String = new String(); // Creating a String Variable to pass URL
switch(e.target.parent.name) // Calling the instance name
{
// here it's checking if the name of the instance is "a_btn"
case "a_btn": // if the condition is true
url = "http://www.A.com/"; // do this
break; // and exit the loop
case "b_btn": // if the condition is true
url = "http://www.B.com"; //do this
break; // and exit the loop and so on.......
case "c_btn":
url = "http://www.C.com";
break;
default:
trace("None of the statement is true.")
}

// Once the conditional statement finishes
var myRequest:URLRequest = new URLRequest(url); // created a url request
navigateToURL(myRequest); // open the url request
}


One thing you have to be careful about he is the colon(:). The case statement ends with colon not with semicolon as other statements does.
And that is it. All the Mouse Click Event calling same function. The function check which Mouse Click Occurred base on that you call other functions of task.

No comments:

Post a Comment