If you’ve tried to load one swf into another and found that the loaded clip’s timeline code has disappeared, you’re not alone. Fortunately, the explanation is simple.
Usually what happens is, you’ve tried to cast the reference to the loaded swf to its document type, like so:
var page : MyDocumentClass = loader.content as MyDocumentClass;
page.doSomeMethod();
If doSomeMethod, for example, plays an animation on the timeline that you have governed with “stop” commands, or that calls methods in the document class, you’ll find that it doesn’t work.
Why? Because you’ve embedded the class definition in the parent movie, and it doesn’t know about the timeline code. Think about it: adding timeline code to a movie effectively makes that movie a subclass of its document class. When you embed a reference to the document class in the parent, the version associated with the child movie (with the timeline code) isn’t used.
An associated problem is that you’ve defeated some of the key reasons for modularizing your sites – to make updates easier, and load code only when it’s needed, not before. Embedding the document classes of your loaded movies defeats the former – because you have to recompile the parent as well as the child when you update the child, and the latter – because you’re loading all the child classes in the parent.
How to solve the problem, then? use interfaces. Make all of your document classes implement a single interface and make absolutely sure that no references to the document classes exist anywhere in the parent movie.
For example, here’s a child movie class:
public class MyChild extends MovieClip implements IChild{
public function transitionIn():void{
gotoAndPlay(’somewhere’);
}
}
As you can see, MyChild implements IChild, an interface:
public interface IChild extends IEventDispatcher{
function transitionIn():void;
}
Now, in your parent movie, you’ll use something like this:
private function movieLoaded(evt:Event):void{
var child : IChild = loader.content as IChild;
child.transitionIn();
}
Notice that you’re calling a method on the interface, not the document class. In fact, the parent movie should be completely agnostic where the doc classes are concerned. The interface is enough.