17 May 2007

Accessing class function using a string

Here's a piece of dodgy looking code - but it works!?

I've got a class called "ServiceLoader" which contains many service calls, I also have buttons which correspond to these service calls. I've named the buttons as the ServiceLoader function names e.g. "getRecord" button corresponds to the "getRecord" function in my ServiceLoader class.

So I can grab the button name, which is a String and then call a function within the ServiceLoader class using associative array syntax:

var func:String = activeButton._name;
ServiceLoaderInstance[func](arg1,arg2);

I'm not sure how "correct" this is, but it works. Any thoughts?

1 comment:

Anonymous said...

I don't think it is actually too dodgy? Presumably this is AS2 or AS1. I never really did AS1, so this might not be wholly accurate, so from what I think I know.... Basically all classes are dynamic in AS1. A class is implemented as an array of functions - hence the ability to use an associative array to call a class function.

While your approach is probably convenient and requires little code, you might want to ask yourself how maintainable it is, or indeed how sensible it is. In AS2, I think I'd be looking to using events and have my service loader instance listening for button events ? (Heading more towards Observer design pattern and maybe MVC)

From 2 lines of code I'm not entirely clear what your trying to acheive. Is this a stab at the Command Pattern (rather directly implemented)? ... http://www.cs.mcgill.ca/~hv/classes/CS400/01.hchen/doc/command/command.html
Which in my Head First book uses a generic (programmable) remote control as a metaphor