What happens when something leaves the stage?

I noticed that problems can occur when something leaves the stage. At times when a movie clip leaves the stage you will want to clean up or put things in order. I found there are two events that occur when a display object leaves the stage: REMOVED and REMOVED_FROM_STAGE. These have the potential to be very useful.

Here’s a short snippet of code to show how they work. Imagine you have a movie clip named box_mc. The script below adds a the clip to the satge, then assigns a CLICK event listener to it. When the box_mc is clicked it removes itself from the stage. This enabled by adding the REMOVED_FROM_STAGE event listener.

var box_mc:MovieClip = new Box();
addChild( box_mc );
box_mc.addEventListener( MouseEvent.CLICK, click_box );
box_mc.addEventListener( Event.REMOVED_FROM_STAGE, remove_me );

function click_box( event:Event ):void {
	trace( "Click box" );
	removeChild( box_mc );
}

function remove_me( event:Event ):void {
	trace( event.target + " has been removed from the stage" );
}

Here’s another exmaple. Imagine you have a class that is used as he base class for a MovieClip. That is the class is set as the Base Class for a MovieClip Symbol in your library. This class might create objects that live on after it is removed from the stage.

To take care of these object you can give your class a destroy() method and add an event listener for REMOVED_FROM_STAGE. This way the clip takes care of cleaning up after itself.

Here’s an example of a class with a destroy() method set up as described:

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

	public class OrangeBox extends MovieClip {

		public function OrangeBox() {
			addEventListener( Event.REMOVED_FROM_STAGE, destroy );
		}

		public function destroy( evt:Event ):void {
			trace( "Destroy the Orange box" );
		}
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *