This turned out to be trickier than I had imagined. After many thrown errors and some masterly Google searching by a student of mine, we discovered that the secret lies in dispatching an event from down inside the loaded SWF. This event needs to bubble down to the parent, or container SWF, that originally loaded the one you want to close.
Now, these loaded SWFs are quite simple. The tricky bit is the button, which exists inside the loaded SWF. The problem we solve here is how to make that X button unload the SWF that contains it.
You need to upgrade your Flash player (v.9 or later) to view this example.
The function in the parent SWF that loads the child SWF needs to spawn a listener:
function loadSWF1(e:MouseEvent):void {
myLoader.load(new URLRequest("one.swf"));
addChild(myLoader);
myLoader.addEventListener("killMe", killLoadedClip);
}
The "kill" function also must be in the parent SWF:
function killLoadedClip(e:Event):void {
myLoader.removeEventListener("killMe", killLoadedClip);
removeChild(myLoader);
}
And now, the magical event dispatcher, which must be in the child SWF:
parent.dispatchEvent(new Event("killMe"));
That line can appear in the function for the Close button. Or, alternatively, it can appear on a frame (say, after a fade-out animation has run). It sends the text "killMe" to the parent (one step), where the listener catches it and therefore calls the function named killLoadedClip.
The best guide I have seen to ActionScript 3.0 events is this one: Taking a Closer Look at the ActionScript 3.0 Event Framework, by Daniel Apt.
DOWNLOAD The files can be downloaded from this folder.
Education use: This package was created as an example for my journalism students. It is not intended to be used commercially.
Use and re-use:
Make a Loaded SWF Unload Itself in Flash CS4 (AS3) by Mindy McAdams is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.
Updated 24 April 2010