Archive for July, 2009

Learned Something About Events in ActionScript 3

Saturday, July 11th, 2009

I was recently presented with a multiple choice question that went something like this:

Events in ActionScript 3 represent what type of code?

  1. Synchronous Execution
  2. Asynchronous Execution
  3. Object Oriented Programming
  4. Procedural Programming

Thinking how events allow for loosely-coupled components, I clicked answer #3 and moved on. Like every Flex developer, I use custom events that extend the Event class and deliver a payload to the event handler function. However, here recently, I’ve been working on a project for a client where they used no custom events whatsoever. It is a large project and, architecturally-wise, it is really a mess. Every object has a reference to every other object and they all call methods on each other, or worse, on each other’s children.

Anyway, as I thought back to the question it got me wondering if, despite my constant use of events, I had a good understanding of how Flash’s eventDispatcher class (whose code, unlike the open-source Flex framework, is part of playerglobal.swc and cannot be viewed) works.

I did a quick test in the Flash IDE

  1. addEventListener("myEvent", myEventHandler);
  2. dispatchEvent(new Event("myEvent"));
  3. trace("hello");
  4.  
  5. function myEventHandler(event:Event):void
  6. {
  7.     trace("hello from myEventHandler");
  8. }

Which produced the result:

hello from myEventHandler
hello

So the correct answer to the question above is 1. Synchronous Execution. (Added: or not… see discussion in the comments).

Calling the dispatchEvent method on EventDispatcher (or any class that extends it) causes EventDispatcher to immediately look up the functions that were registered as event handlers and call them in the order they were registered (or in the order of the priority argument passed in when registering the handler via addEventListener).

I don’t know why I didn’t realize this before. I guess I just hadn’t walked it through in my mind or thought events got queued up or something with handlers called when that queue was processed, perhaps on the next frame.