O'Reilly logo

Essential ActionScript 3.0 by Colin Moock

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Event Listeners and Memory Management

As we've seen throughout this chapter, ActionScript's event architecture is based on two key participants: the listener (either a function or a method) and the object with which that listener registers. Each object that registers a listener for a given event keeps track of that listener by assigning a reference to it in an internal array known as a listener list. For example, in the following code (repeated from Example 12-1) the completeListener( ) method registers with urlLoader for Event.COMPLETE events. As a result, urlLoader's internal listener list gains a reference to completeListener( ).

package {
  import flash.display.*;
  import flash.net.*;
  import flash.events.*;

  public class FileLoader extends Sprite {
    public function FileLoader () {
      var urlLoader:URLLoader = new URLLoader();
// Register completeListener()
urlLoader.addEventListener(Event.COMPLETE, completeListener);
      urlLoader.load(new URLRequest("someFile.txt"));
    }

    private function completeListener (e:Event):void {
      trace("Load complete");
    }
  }
}

By default, any object that has a reference to a listener maintains that reference until the listener is explicitly unregistered via the removeEventListener( ) method. Furthermore, the object maintains its reference to the listener even when no other references to the listener remain in the program. The following simple class, AnonymousListener, demonstrates. It creates an anonymous function and registers that function for MouseEvent.MOUSE_MOVE ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required