Liquid Interfaces in AS3

I’ve had to answer this at least three times in the last month so I’m assuming it’s a useful piece of code.

When creating liquid interfaces in ActionScript 2 you simply let your object listen to the stage for changes, like so:

1
2
3
4
5
6
7
Stage.addListener(this);
 
...
 
private function onResize() {
   this.mc_background._y = Stage.height
}

In ActionScript 3 the stage is accessible as a property in all classes inheriting from DisplayObject. Useful, but here is where the trouble begins for most people. If you try this inside your class:

1
2
3
4
5
6
7
stage.addEventListener(Event.RESIZE, drawObject);
 
…
 
private function drawObject(e:Event){
   _background.width = stage.stageWidth;
}

…it will throw an error, because the stage object is only available after your object has been added to the display list. So what do we do?

The simplest thing is to add a listener for when the object is added, and when that is done remove is and replace it with a listener for resize:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Add initial resizer
addEventListener(Event.ADDED_TO_STAGE, drawObject);
 
…
 
private function drawObject(e:Event){
 _background.width = stage.stageWidth;
 
 if(e.type == Event.ADDED_TO_STAGE){
    // remove initial listener
    removeEventListener(Event.ADDED_TO_STAGE, drawObject);
 
   // Add permanent listener
   stage.addEventListener(Event.RESIZE, drawObject);
 }
 
}

By doing this we get the same behavior as in AS2 but with the added benefit of a resize upon initialization.

I really should attempt to finish the animation tutorials. I’ll write some of them up during vacation, promise :)

Here’s also a video I found on the subject: