Wednesday, April 20, 2005

AsBroadcaster for custom events

The undocumented feature AsBroadcaster in Flash MX 2004 allows for custom event dispatching/handling. If you want an object to be able to dispatch events, you can do it in the class' constructor like this:


Or, if you want, anywhere else, like this:


This will add, among others, the methods addListener() and broadcastMessage() to the object in question. Thus, if you want the object do dispatch an event, just add the following code to the class code:


To register an object as a listener for the event, do the following:


The listener object must then define a method called onCustomEvent in order for it to be able to respond to the event. The object "object" can however not be type declared. That is, if I define it like this, it won't work (getting an error message saying "There is no method with the name 'addListener')":

var object:MyEventCaster = new MyEventCaster();

but if I instead write just

var object = new MyEventCaster();

it works fine. I suppose it is because the event-methods are dynamically added to the object class, and thus, can't be found at compile-time. If the variable isn't properly declared, the compiler won't be able to perform the check.

A more detailed tutorial is provided by FlashGuru. I just wanted to stress that the event-dispatching object cannot be declared with type. Oh, and in Flash MX it is called ASBroadcaster, whereas in Flash MX 2004 it is AsBroadcaster.

UPDATE: I realised that by creating empty methods for the AsBroadcaster-methods to be used, one can still type declare the objects. That is, in the event dispatching class, add the code

function broadcastMessage(){}
function addListener(obj){}

..etcetera. These methods will then be overridden by the call to


... and it is now possible to use the object declared with type.


Post a Comment

<< Home

En blogg kan være et godt verktøy for en som i litt for stor grad glemmer de små og store tingene som utgjør livet. Dette er min reserve- hukommelse.