Learned Something About Events in ActionScript 3

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.

7 Responses to “Learned Something About Events in ActionScript 3”

  1. greg h Says:

    Hi Jamie,

    The correct answer is 2. Asynchronous Execution.

    This is a good concept to understand.

    The order of the traces in your example did not have to be in that order. For instance, if you replace your dispatchEvent with a statement to load an external file, the latency of the network call may result in the complete event being after the subsequent statements like your trace(“hello”);

    Synchronous means blocking. When a synchronous operation is being performed, the code pauses and waits for the completion of the synchronous operation before moving on to execute subsequent statements.

    Oddly, one of the best explanations is in the AIR docs (because developers can choose to execute AIR database calls either synchronously or asynchronously). See this page in the docs:
    Using synchronous and asynchronous database operations
    http://help.adobe.com/en_US/AIR/1.1/devappsflex/WS5b3ccc516d4fbf351e63e3d118666ade46-7d39.html

    The “Programming Adobe ActionScript 3.0″ doc does include this:
    http://livedocs.adobe.com/flash/9.0/main/00000096.html
    Asynchronous: A program command such as a method call that doesn’t provide an immediate result; instead it gives a result (or error) in the form of an event.

    And the earlier, but still great Colin Moock’s “ActionScript for Flash MX: The Definitive Guide” has the following:

    Event-Based Asynchronous Code Execution
    http://www.adobe.com/devnet/flash/articles/actionscript.html

    Event-Based Asynchronous Code Execution
    “Some code does not execute in a predetermined sequence. Instead, it executes when the ActionScript interpreter notices that an event has occurred. Many events involve a user action, such as clicking the mouse, resizing the movie, or pressing a key. Other events happen without user intervention, such as a sound completing or an XML document loading. Just as the playhead entering a new frame executes synchronous code attached to the frame, events can cause event-based code to execute. Event-based code (code that executes in response to an event) is said to be executed asynchronously because the triggering of events can occur at arbitrary times.

    hth,

    g

  2. Alan Says:

    Thinking about it, I don’t think that multiple choice question is a good question. I would believe that the best answer is #2.

    I chose to say ‘best’ and not ‘correct’, because I believe that you just demonstrated how an event can be used in a synchronous manner, but the purpose of events is to enable an app to execute asynchronously.

    Example: When using an app like Photoshop, when I save an image the app will pause while it writes the file to disk – locking out any user interaction until it is complete. This is synchronous behavior. In a Java or Flash app, the user may be constantly reading and writing to a remote database. If Flash was synchronous, then the app would pause until a database read or write was completed.

    I see that question as a bad question. As you pointed out, Flash’s event structure may work synchronously, but I believe the intent is for an app to run synchronously.

  3. Kim Says:

    The answer is #2 because the whole idea of the event system in Flash (as with other langauges) is asynchronous code execution – the premise that code does NOT have to follow a pre-ordained sequencer of execution and is independent of time.

  4. Jamie McDaniel Says:

    Thanks for providing insight Kim & Alan. I wish I could remember how the question was phrased exactly, because I am probably missing some important word. Also, I should say that this was not an official Adobe question, like on a certification test. It was the ActionScript 3 test over at oDesk.

    Alan, what you describe as allowing an app to run asynchronously are server calls. I’ve seen the word “asynchronous” used many times in the official documentation for HTTPService, WebService, and RemoteObject in Flex. For example, when you call the send() method on HTTPService, the Flash player calls the service and then continues to execute code, not waiting around for the result. The HTTPService’s ResultEvent is dispatched only when the server call returns successfully at some future time. (For anyone following this discussion, here is a forum post where Adobe employee Tom Lane explains it better than I can.)

    Kim, point taken. Event-driven programming versus old-school BASIC and other languages where code execution flowed from line 1 to the end of the program and then it looped back. However, what I wondered about the question was what I demonstrated — that dispatchEvent() is a synchronous operation. Assigning an event handler function to an event and then dispatching that event is exactly the same as calling the event handler function directly (not taking into account such things as the priority argument passed in via addEventListener, or the capture/bubble phases, or event.stopPropagation(), etc.) Do you agree?

  5. Jamie McDaniel Says:

    @greg, Apologies… your comment got held up for moderation due to the number of links, so I did not see it until just now. (I’ve since upped the number.) Thank you for the helpful explanation. I understand the examples you and Alan gave about Event.COMPLETE and ResultEvent.RESULT being dispatched at a future point in time after calls to Loader.load(), HTTPService.send(), etc. I think I was uncertain about what happens once the event is actually dispatched. And it seems EventDispatcher immediately looks up the handlers and executes them (i.e. synchronous code execution) before proceeding to the line of code following dispatchEvent().

    But I am now certain that you all are correct in that the answer the test was looking for was 2. Asynchronous execution. The question was referencing the fact that calling certain methods does not provide immediate results, but rather the result (or error) is returned via an event that is dispatched at some future, arbitrary time — hence asynchronous execution. Did I get it? :-)

  6. Jamie McDaniel Says:

    More insight from Professional Adobe Flex 3, page 20: “The Flash Player follows a single-threaded execution model, with the exception of specific advances related to Flash Player 10. This means that event handling is synchronous, which may take some getting used to for users of multithreaded languages. A single-threaded model has the advantage of simplified event propagation and debugging, and since there are no race conditions or deadlocks to worry about, it simplifies the coding of certain class structures such as the Singleton design pattern.”

  7. Jamie McDaniel Says:

    Update: I retook the test today and noted the exact wording of the question. It was “Which nature of ActionScript is depicted by the use of Events: Synchronous, Asynchronous, Procedure oriented, or Object oriented?”

Leave a Reply