Posts Tagged Interfaces

Another good use of interfaces

Earlier this year, I came to understand how to use interfaces in ActionScript 3. I used them in a particular case where polymorphism was needed but that was it since then. Last week I realized that I could use them in much more case than that. I actually need them in nearly all of my projects.

As I have mentioned in previous post, I always structure the websites I program in the same way. I make one swf file for the preloader, one swf file for the shell (container of navigation that load every sections) and one swf for every section (page) in the site. Sometimes, the preloader needs to inform the shell (main movie) when to start its intro animation. An example of that is the don’t discover Loyalist contest website. When you first load the page, the flash file looks like it is just sitting there waiting for you to click on the start button. But actually it is already preloading the main swf file. That leads to two scenarios; either the user clicks on start and the main movie is not loaded yet so it will start only when it is fully loaded or the user clicks when the main swf is fully loaded and the preloader has to tell the main movie that it can start. I used to disable the strict mode of the compiler in order to call a public method of the main swf document class. That worked fine since I never have so much code involved for a preloader but then I hit a wall.

I came across the same problem when loading external Flash file from which I wanted to use methods. The compiler just didn’t want me to do so. When I started coding in AS3, I, at first, found the compiler to be a bit severe, but I kinda like it now, it finds problems before they arise, so that’s why I don’t want to turn of strict mode for my main movie, where I have thousands of line of code. So I had to find another solution, I tried to import the document class of my external swf with an import statement but the compiler didn’t like it that much because it wasn’t finding classes for Sprites on the stage. That’s when I remembered about interfaces.

Interfaces permit you to ensure that some classes contains some methods. So in my external swf document class I made certain it implemented the interface I was going to us and in my main movie I type casted the loader.content to that interface (Type).

1
2
3
import com.zedia.interfaces.ISection;
 
var mySection:ISection  = ISection(loader.content);

Now the compiler was happy. I could load external swf and use its methods. One trouble was left; I wasn’t able to add my new content to the display list because my main movie didn’t know that the external swf was extending a DisplayObject. All I had to do to solve this was to type cast my external swf to a Sprite when I added it to the display list like this:

1
addChild(Sprite(mySection)) ;

That really did the trick and now I am going to use interfaces in most of my projects.

, ,

12 Comments