The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
ActionScript: Calling a function by name

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Jay Fields

Posts: 765
Nickname: jayfields
Registered: Sep, 2006

Jay Fields is a software developer for ThoughtWorks
ActionScript: Calling a function by name Posted: Jul 8, 2008 7:44 AM
Reply to this message Reply

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.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Jay Fields
Latest Posts From Jay Fields Thoughts

Advertisement
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
}

Read: ActionScript: Calling a function by name

Topic: Rapid Test Feedback Previous Topic   Next Topic Topic: Ruby Book Sales Surpass Perl &#38; Python

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use