PDA

View Full Version : using for loop to set function names from an array



count_schemula
March 13th, 2009, 06:25 PM
// array with function name parts
var functionNames:Array = ["something1","something2","something3"];

// create functions looping through array
for (var i:Number = 0; i <= functionNames.length; i++){
var funcName1:String = "prefix_"+functionName[i]+"_suffix";
function funcName1(evt:MouseEvent){
// important things with Demetri Martin
}
var funcName2:String = "prefix_"+functionName[i]+"_othersuffix";
function funcName2(evt:MouseEvent){
// important things with Demetri Martin
}
}

I've tried some various things (including "this"), but basically, I need to loop through data held in arrays to create several dynamically named functions on the the fly.

Joony5
March 14th, 2009, 08:51 AM
Close. Something like this should work. If it's in a class, the class will need to be declared "dynamic" or you can't dynamically add methods or vars at runtime. Also, note the difference between functionName and functionNames. All you have to do is swap the parameter from a string to an event and setup your listener.


var functionNames:Array = ["something1", "something2", "something3"];

var functionName:String;
var l:uint = functionNames.length;
for(var i:uint=0;i<=l;i++){
functionName = "prefix_" + functionNames[i] + "_suffix";

this[functionName] = function(str:String):void{
trace(str);
};
}

this["prefix_something1_suffix"]("hello world");

This, however, probably isn't the best solution to the problem, but I can't comment on that without knowing the whole problem.