Hi guys,
I've just added an experimental new feature to the development branch: an overhauled event mechanism. I'd be happy about your comments! Does this make sense? Do you like it / not?
1) Automatic Event Pooling
You can now dispatch events with this line instead of the old one:
object.dispatchEventWith(Event.TRIGGERED, true);
// equivalent to:
object.dispatchEvent(new Event(Event.TRIGGERED, true));
Besides having to type less, this has the advantage of using a pool of event objects behind the scenes. The garbage collector will be happy about that. =)
This only works for instances of "Event", though. But here's where the next change comes in handy:
2) Event Data
The standard event class now has a new property "data" of type "Object", which can contain any value you like. In many cases, this allows you to avoid creating a custom event; a new event type string will do.
addEventListener("customType", onEvent);
dispatchEventWith("customType", false, "testData");
private function onEvent(event:Event):void
{
trace(event.data); // prints "testData"
}
OK, this is handy, but not a revolution. But the third change is what makes this system extraordinarily handy:
3) Variable Parameters for Listeners
This feature is best shown with sample code:
addEventListener("customType", onEvent);
dispatchEventWith("customType", false, "testData");
// version 1:
function onEvent():void
{
// I'm not interested in the event object, just that it has happened
}
// version 2:
function onEvent(event:Event):void
{
// now you can access the event object, too
trace(event.data); // -> "testData"
}
// version 3:
function onEvent(event:Event, data:String):void
{
// now you've got all data easily accessible
trace(data); // -> "testData"
}
Pretty neat, isn't it? That removes a lot of boiler plate code. Look at these examples:
addEventListenerWith(Event.ADDED_TO_STAGE, onAddedToStage);
function onAddedToStage():void
{
// have you ever used the event here?!
}
addEventListenerWith(Event.ENTER_FRAME, onEnterFrame);
function onEnterFrame(event:Event, passedTime:Number):void
{
// passedTime is directly available
}
addEventListenerWith(KeyboardEvent.KEY_DOWN, onKey);
function onKey(event:Event, keyCode:uint):void
{
// in most cases, I don't need anything but the keyCode.
}
That's it!
I'd be happy about your feedback! =)