View Single Post
Codemonkey's Avatar Codemonkey Codemonkey is offline Super Moderator 2006-11-06 #21 Old  
018 - __resolve your properties and methods
Last edited by Codemonkey : 2006-11-11 at 02:20.
 
A less known and even less used feature in actionscript is the __resolve method.

If you declare a method called __resolve on your class and someone tries to call a property or method of your class that doesn't exist, flash will look for a __resolve instead and call that one. You will get a parameter with the name of the unknown property/method that the user is trying to call. In addition, you can use the arguments variable inside __resolve to uncover any arguments the user passed.

You can call properties/methods that don't exist on an object when:
  1. Your class was declared dynamic
    ActionScript Code:
    1. dynamic class MyClass {
    2. function __resolve(name:String) {
    3. // do something
    4. }
    5. }
    6. var instance:MyClass = new MyClass();
    7. instance.unknownFunction()
  2. You use an Object directly
    ActionScript Code:
    1. var o:Object = new Object();
    2. o.__resolve = function (name) {
    3. // do something
    4. }
    5. o.unknownFunction()
  3. You typecast an instance of your non-dynamic class as Object (this won't work in AS3.0 though)
    ActionScript Code:
    1. class MyClass {
    2. function __resolve(name:String) {
    3. // do something
    4. }
    5. }
    6. var instance:MyClass = new MyClass();
    7. Object(instance).unknownFunction()
__resolve can be useful in case you are creating dynamic classes for distribution and you want people to know when they called a non-existent function - which the compiler would've done if your class wasn't declared with the keyword dynamic. Or you could use __resolve to forward method calls to a server or act as an adaptor to other objects. In doing so you can also log all methods being called through __resolve in a single place. Another use is when you have a 'decorator' and you need to forward dynamic methods 1-on-1 to the 'decoratee'.

Be cautious though, __resolve doesn't *always* work as you would expect and you should have a very specific reason where you think __resolve is the solution.