After reading Benjamin Mace's recent article about _root and scope, we found ourselves talking about different ways to handle issues of scope and event management. There's a very interesting utility object, called Delegate, included in Flash (I believe it's been there since the MX 2004 Ellipsis update) and is included in Flash 8.
The Delegate object's purpose is to call a specific function and apply a specific scope to that function call. For example, if you had an event callback that was going to two different components, each with a method called "onMyEvent", you could use a Delegate to ensure that the onMyEvent call was used within the specific scope of each of the components.
Put more plainly, generic functions in Flash are like toothless drunkards that may or may not know their responsibilities or even their own name. Whereas, a Delegate is like a responsible homeowner. When it has business to tend to, it does so in its own home and only in his own home.
Most Flash developers are aware of scope issues relating to LoadVars or XML onData and onLoad events. When processing these events, the scope for the event is the LoadVars or XML object itself and not the class that instantiated it. For example:
In the example above, the parseData method is never called, because the onData event in the LoadVars object doesn't have a reference back to the class that instantiated it. However, if we use our responsible homeowner (the Delegate) instead of this unnamed function literal, we can force this event to be handled in the correct scope.
The Delegate class can be found in the package mx.utils.Delegate. It has just one static method called "create". The two arguments passed into the Delegate.create method are 1) scope (a reference to an object that you want the function applied to) and 2) a reference to a function. The Delegate will then return a fine upstanding young function with a home, a mortgage and known responsibilities.
We can rework the previous code to take advantage of the Delegate and get the LoadVars object to handle its event within the scope of our DataProxy class.
It's safe, it's simple and it's powerful. Whenever you have to pass a reference to a function into another object, in most cases using a Delegate is the way to go. This object works great with setInterval, setTimeout, and Component.addEventListener.
In Flash 8, the Delegate class is considered part of the Components Language Reference. It was originally developed for use in v2 components, but it's usefulness extends far beyond prebuilt components.