Select frame 1 of the actions layer, and open the Actions panel (F9). Delete the existing code in the Script pane, and add the code shown in Listing 28-5.
Listing 28-5: An Example of a MovieClipLoader Object at Work
1. var cbtLoad:mx.controls.Button;
2. var cbtUnload:mx.controls.Button;
3. var tImg:TextField;
4. var mcHolder:MovieClip;
5.
6. var mcl:MovieClipLoader = new MovieClipLoader();
7.
8. var oLoader:Object = new Object();
9. oLoader.onLoadError = function(mc:MovieClip, sError:String):Void {
10. trace("A loading error has occurred: "+ sError);
11. };
12. oLoader.click = function(oEvent:Object):Void {
13. var sLabel:String = oEvent.target.label.toLowerCase();
14. if(sLabel == "load image"){
15. mcl.loadClip(tImg.text, mcHolder);
16. } else if (sLabel == "unload image"){
17. mcl.unloadClip(mcHolder);
18. }
19. };
20.
21. mcl.addListener(oLoader);
22.
23. cbtLoad.addEventListener("click", oLoader);
24. cbtUnload.addEventListener("click", oLoader);
In lines 1-4, the data types of existing elements on the Stage are declared. In line 6, a new MovieClipLoader object named mcl is created, using the constructor function of the MovieClipLoader class.
In line 8, a listener object named oLoader is created. This object will receive events that are broadcasted from the mcl object, as well as the Button components you used previously.
In lines 9 through 11, an onLoadError() handler is defined for the oLoader object. This handler is specific to MovieClipLoader listeners. If there is an error during the loading of an external asset via the MovieClipLoader object, mcl, this handler will be invoked. The handler can accept two parameters, the MovieClip instance receiving the loaded asset (mc) and an error message indicating what went wrong with the loading (sError). In our example, on line 10, we simply throw the error message to the Output panel.
In lines 12 through 19, the click() method of the oLoader object is defined. (Note that this is effectively the same oLoader object we used in previous exercises of this chapter.) The oLoader receives events from the cbtLoad and cbtUnload instances (lines 23 and 24). When either Button instance is clicked, the click() handler in lines 12 through 19 is invoked.
In line 21, the oLoader object is added as a bonafide listener of the mcl object. Without this line of code, the mcl object would not know to broadcast events to the oLoader object.
The difference from our previous exercises occurs primarily in line 15: Instead of using the loadMovie() method, the loadClip() method of the MovieClipLoader class is used with the mcl object. loadClip() takes two parameters: the URL of the SWF or image asset to load, and the MovieClip object that will hold the asset.
In line 17, the unloadClip() method of the MovieClipLoader class is used to unload the content from the mcHolder instance.