Passing Variables to A Function in ActionScript 3
I have asked and have been asked, “How do I pass a variable to a function when using the addEventListener to call a function in ActionScript 3?”
Passing a variable to a function in ActionScript 2 was a fairly simple task. However, it is not so easy using ActionScript 3. There are a few more things you must do first.
In ActionScript 2, passing a string variable looked like this.
my_btn.onRelease = function(){
doThis("whatever variable you want goes here");
}
function doThis(a:String){
trace(a);
}
In ActionScript 3, this is what I need to do to get the same results. I initially wrote the example below thinking at some point, I will have several buttons that the user will interact with such as a navigation menu.
var b:Array = [b1_btn, b2_btn, b3_btn];
var a:Array = ["zero","one","two"];
for (var i:int = 0; i<b.length; i++) {
b[i].addEventListener(MouseEvent.CLICK, clickedOne);
function clickedOne(e:MouseEvent):void {
for (var j:int = 0; j<a.length; j++) {
if (e.currentTarget.name == b[j].name) {
doThis(a[j])
}
}
}
}
function doThis(v:String):void {
trace(v);
}
If you have any questions just drop me a line.
UPDATE!!!
There’s more than one way to solve this problem.
Thanks to kcreation for this solution.
var btns:Array = [b1_btn, b2_btn, b3_btn];
var a:Array = ["zero","one","two"];for (var b in btns) {
btns[b].name = b;
btns[b].addEventListener(MouseEvent.CLICK, clickedOne);
}function clickedOne(e:MouseEvent):void {
var b:int = int(event.currentTarget.name);
doThis(a[b]);
}function doThis(v:String):void {
trace(v);
}
Thanks to Mykola Bilokonsky for this solution.
var buttons:Array = [b1_btn, b2_btn, b3_btn];
var dict:Dictionary = new Dictionary();
dict[b1_btn] = “String Argument”;
dict[b2_btn] = new MySampleMovieClip();
dict[b3_btn] = 7for each (var b:MovieClip in buttons) {
b.buttonMode = true;
b.addEventListener(MouseEvent.CLICK, myHandler);
}function myHandler(e:MouseEvent):void {
var myVariable = dict[e.currentTarget];
}
About this entry
You’re currently reading “Passing Variables to A Function in ActionScript 3,” an entry on homer gaines
- Published:
- 11.07.08 / 4pm
- Category:
- ActionScript 2.0, ActionScript 3.0, Flash, Resources
7 Comments
Jump to comment form | comments rss [?] | trackback uri [?]