Jose Sandoval Google
 Resume     Book     Software     Drawings     Home     Subscribe to RSS feed Search Web Search

AS3 and anonymous event handlers
Tuesday, December 29, 2009

Event listener models are not new; however, AS3 event listeners are new to me.

I've developed a couple of application in Java Swing and Eclipse RCP, and both frameworks rely heavily on the event dispatch/listener model. AS3 being a full fledged Object Oriented programming language also uses it.

This week I continue fixing a few bugs for one the Flash projects I'm working on. Our application aggregates content from Flickr, YouTube, and Twitter and displays it all in one place. Everything coming into the page is piped through REST calls (HTTP GET requests) as XML structures. Making GET requests and consuming XML structures is easy in Flash, because AS3 provides APIs for HTTP connections and XML parsing.

To load an image in our application we need to make 2 Flickr API calls: first, get the sizing information of a particular image; second, load the desired size of the particular image. In both cases, I need to make an HTTP call and then wait for the response to complete, for which I need 2 event listeners registered. Registering events is all fine and all, but I wanted to do something I've been doing for a while in Java--creating anonymous event handlers on the spot.

If you were wondering how to do this, following is a snippet of code to demonstrate the :
function loadImage(FLICKR_KEY:String, PHOTO_ID:String):void {
var sizeURLRequest:URLRequest =
new URLRequest(""
+ "services/rest/?"
+ "&api_key="
+ "&photo_id="
var sizeURLLoader : URLLoader = new URLLoader();
sizeURLLoader.addEventListener(Event.COMPLETE, function (event:Event):void {
var sizeXML : XML = XML(;
var targetURL : URLRequest = new URLRequest(sizeXML[0].sizes[0].size[4].@source);

imageLoader = new Loader();
imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, showImage);

The anonymous listener is the statement sizeURLLoader.addEventListener(Event.COMPLETE, function (event:Event):void { ... }. This is the same as implementing an interface as an anonymous class, which is what would be familiar to you if you were a Java developer.

Note that showImage could also be implemented as an anonymous listener, but in this case there's too much logic to display the image and therefore is a separate function that looks as follows:
private function showImage($event:Event):void {
// Display image here...

11:47 PM | 0 comment(s) |


This page is powered by Blogger. Isn't yours?

© Jose Sandoval 2004-2009