Tuesday, July 08, 2008

ActionScript: Calling a function by name

In Ruby I can call a method using it's name (as a string) using send.

def hello
"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.

<mx:MenuBar id="myMenuBar" labelField="@label" itemClick="menuHandler(event);">
<mx:XMLList>
<menuitem label="Submit" handler="submit"/>
<menuitem label="Reset" handler="reset"/>
</mx:XMLList>
</mx:MenuBar>

private function menuHandler(event:MenuEvent):void {
this[event.item.@handler](event);
}

private function submit(event:MenuEvent):void {
// do submit logic
}

public function reset(event:MenuEvent):void {
// do reset logic
}

2 comments:

Note: Only a member of this blog may post a comment.