So let’s create a new class called DynamicReflection. This new class will be quite different from the first one. First we’ll take advantage of the RENDER event that we can call from the stage.invalidate() method. This will allow us to draw a reflection only when we need one and so saving some CPU usage. Here is our first draft:

import flash.display.*;

Import the Display package and events package.

private var TargetDisplayObject:DisplayObject = null;
private var needsRedraw:Boolean;
private var W:Number;
private var H:Number;

Four member variables to start, one to store the target object, one Boolean to drive our RENDER event, and two for the width and height. Now the constructor:

public function DynamicReflection(Target:DisplayObject = null){//parameter is optional
if(Target != null){//if we got a DisplayObject
TargetDisplayObject = Target;//then set our member variable
redrawReflection(); //we have an object so we can draw a reflection when possible
addEventListener(Event.RENDER, initReflection);//we listen for a RENDER event
addEventListener(Event.ADDED_TO_STAGE, initReflection);
//make sure we draw our reflection if we need it when added on the display list

Flash does not dispatch a RENDER event by default, we have to make a call to stage.invalidate() to force Flash to dispatch this event.

public function set target(Target:DisplayObject):void{
TargetDisplayObject = Target;//set our member variable
redrawReflection(); //ask to redraw our reflection

The setter method will allow us to change the target object on the fly thus allowing us to reuse a DynamicReflection instance.

private function redrawReflection():void{
needsRedraw = true;//set to true so we'll need to redraw the reflection
//next time a RENDER event is dispatched
if(stage){//if the reflection instance is on the display list
stage.invalidate();//ask for a RENDER event to be dispatched

Basically we force Flash to dispatch a RENDER event but we still use a Boolean to check if our reflection needs to redraw itself. If another object requested the RENDER event we don’t want our reflection to redraw itself if it doesn’t need to.

private function initReflection(e:Event):void{
if(stage && TargetDisplayObject.visible && needsRedraw){
//if there's a valid stage and if the target object is visible and if we need to redraw the reflection
needsRedraw = false;//then we won't need to redraw the reflection anymore
createReflection();//and here we finally draw or redraw the reflection

The createReflection method is the one that will draw the reflection but by using the RENDER event we make sure that this function will always run only once and only when necessary. Without this we would have to call the createReflection method each time we make a change in the DynamicReflection instance thus running the same createReflection method many times. Now we can add more setters method (we’ll create the getters too).