PDA

View Full Version : How to create a reference to variable/function using strings



mu061686
September 18th, 2009, 08:07 PM
Hi guys,

I'm wondering how I can create a reference to a function/variable by using strings. Sorry if I'm not explaining the problem well, but let me show you what I mean in an example:

You can create a reference to a class using strings by using the getDefinitionByName as follows:

var classRef:Class = getDefinitionByName("myClass") as Class;
var myClass1:classRef = new classRef();

Similarly, how do you refer to functions and variables?

The reason why I want to know is because I'm trying to implement a function which takes in the event handler name as the parameter, and what the function essentially does is that it adds an event listener with the associated handler (based on the parameter) to an object, something like this:

public function addListener(handler:String):void {
mc.addEventListener(Event.ENTER_FRAME, "on" + handler);
}

public function onEnterFrame(event:Event):void {
// do something
}

So if handler = "EnterFrame", the addListener function should assign the onEnterFrame handler to the listener being added.

Thank you very much in advance!

nortago
September 19th, 2009, 05:32 PM
Hey bud,

This'll solve your problem




function helloWorld():void{

trace("hello");

}

this["helloWorld"]();

//or

this["helloWorld"].call();

thatsasif
September 20th, 2009, 03:06 AM
you can do straight away with function as argument...



public function myaddListener(handler:Function):void {
mc.addEventListener(Event.ENTER_FRAME, handler);
}
function enterf(evt:Event):void {
trace("enterframe");
}
myaddListener(enterf);


or if you want to pass event type as parameter then


function myaddListener(me:String, handler:Function):void {
mc.addEventListener(me, handler);
}
function mev(evt:MouseEvent):void {
trace("clicked");
}
myaddListener(MouseEvent.CLICK, mev);

mu061686
September 20th, 2009, 05:44 AM
Those tips are awesome. Thanks guys!