This post originated from an RSS feed registered with Ruby Buzz
by Jay Fields.
Original Post: ActionScript: Calling a function by name
Feed Title: Jay Fields Thoughts
Feed URL: http://feeds.feedburner.com/jayfields/mjKQ
Feed Description: Blog about Ruby, Agile, Testing and other topics related to software development.
In Ruby I can call a method using it's name (as a string) using send.
defhello "hello world" end
send "hello"# => "hello world"
This type of behavior is helpful in scenarios where I store method names as values and execute those methods based on user actions.
In Flex I can store Objects in Views, so I generally don't need this capability. However, I recently wanted to execute a function based on what MenuItem was clicked. The menu was composed of MenuItems that were defined by XML. I couldn't figure out how to get a function into the XML, so i ended up putting the function name as an attribute of each MenuItem. From there, the only trick was figuring out how to call a function on an object if you have the name of the function stored as a string.
It turns out, it's very easy, and exactly what you do in Javascript. All you have to do is pass the string in brackets to the object that has the function defined.
this["methodName"]();
If you're interested in the context, the code below is similar to what my application required.