is supported in part by

August 20, 2004

EventProxy vs mx.utils.Delegate

earlier this year, mike chambers wrote about an EventProxy class for v2 component event handling (see mike's blog post). i mentioned the EventProxy class in essential actionscript 2.0, chapter 12. i also offered a slightly improved version that included more type checking.

since then, macromedia has released the ellipsis update (flash authoring version 7.2). ellipsis includes a new class, mx.utils.Delegate, which replaces EventProxy. so, what's the difference between the two classes?

there are two differences between my updated EventProxy class and the Delegate class: 1) function return value and 2) listeners for actionscript's built-in classes.

1) function return value

when the Delegate class invokes the specified event-handling function, it returns the return value of that function back to the caller (the caller is the component broadcasting the event). however, the EventDispatcher class used by v2 components to broadcast events does not use, nor store the return value of the methods it invokes at event time, so this difference is largely academic.

traditionally, event broadcasting classes do not use the return values of the event methods they invoke, so it is unlikely that EventDispatcher will ever store or use the return values of the event methods it invokes. however, in the unlikely case that EventDispatcher is revised to use the return value of the event methods it invokes, then the Delegate class will be required in favour of EventProxy.

i assume macromedia chose to implement return-value preservation in Delegate as a matter of good form, not out of necessity. by passing the event-method's return value back to the caller, the Delegate class laudably emulates the behaviour of a direct method call, whereas EventProxy does not.

2) listeners for actionscript's built-in classes*

the mx.utils.Delegate class returns a function, not an object, so it can be used to listen to events from actionscript's built-in classes such as MovieClip and XML. in other words, Delegate effectively lets you use listener objects with traditional "function handler"-style actionscript events. for example, using Delegate you can do this:

var obj:SomeClass = new SomeClass();
someMovieClip.onEnterFrame = 
    mx.utils.Delegate.create(obj, obj.someMethod);

given these improvements, and considering that Delegate is now shipped as an official class with Flash MX 2004, you should, in future, use Delegate rather than EventProxy to map component events to arbitrary object method calls. that said, there is currently no practical negative consequence to using EventProxy instead of Delegate, and legacy code need not be updated at this time.

* thanks to p. simek for pointing out this very important and useful feature of mx.utils.Delegate.

Posted by moock at August 20, 2004 03:18 PM