Aug 07 2007
method_missing in ActionScript 3/Flex
method_missing is one of the small bits of Ruby magic that can be used to some really amazing things when used properly, and some really dangerous things when used improperly. Rails dynamic finders are good example of the amazing things that you can do. Here are some others.
It is possible to implement something like method_missing in AS3 using the Proxy class. Here is a relatively simplistic example:
import flash.utils.Proxy; import flash.utils.flash_proxy; dynamic public class BaseProxy extends Proxy { flash_proxy override function callProperty(method: *, ...args): * { try { var clazz : Class = getDefinitionByName(getQualifiedClassName(this)) as Class; return clazz.prototype[method].apply(method, args); } catch (e : Error) { return methodMissing (method, args); } } protected function methodMissing(method : *, args : Array) : Object{ throw( new Error("Method Missing")); } }
The callProperty method is called whenever an undefined method is called on an instance of this class, or any instance of class that extends this class. In the try block we check if the method was defined on the prototype. If it is not found there, we call methodMissing.
So, now if we create another class that extends this one like so
public dynamic class Model extends BaseProxy { public function myMethod (arg1 : String, arg2 : Boolean) : String { return arg1 + " " + arg2; } }
and then run the following trace statements
import flash.display.Sprite; public class MethodMissingExample extends Sprite { public function MethodMissingExample() { var m : Model = new Model(); Model.prototype.runtimeMethod = function (date : Date) : String { return "I was defined at runtime at " + date.toLocaleTimeString(); }; trace(m.myMethod("I exist", true)); trace(m.runtimeMethod(new Date())); trace(m.someMethod(0, false, "x")); } }
You will see the following in the console:
I exist true I was defined at runtime at 09:58:00 PM Error: Method Missing
The first call succeeds because myMethod is defined. someMethod is not defined, so a Method Missing error gets thrown.
Now, if we override the missingMethod in the Model class like so,
public dynamic class Model extends BaseProxy { public function myMethod (arg1 : String, arg2 : Boolean) : String { return arg1 + " " + arg2; } override protected function methodMissing(method : *, args : Array) : Object { return "You called " + method + " with " + args.toString(); } }
and run the same trace statements you will see the following in the console:
I exist true I was defined at runtime at 09:58:00 PM You called someMethod with 0,false,x
