views:

21

answers:

2

Let's assume we have the following class :

public class ImageButton extends MovieClip
{  
    private var bmpNormal:BitmapData;

    // ------- Properties -------
    public function get BmpNormal():BitmapData { return bmpNormal; } 
    public function set BmpNormal(value:BitmapData):void {  bmpNormal = value; } 


    public function ImageButton()
    {
    }

    public function Draw()
    {
        var bm:Bitmap = new Bitmap(BmpNormal); 
        this.addChild(bm);
    }
}

An instance of ImageButton is added with the following code:

var imgBtn:ImageButton = new ImageButton();
imgBtn.BmpNormal = new onstageBMPData(0,0);
imgBtn.Draw();  //<- No need for this line ??
this.addChild(imgBtn);

Now the problem/question is that the draw() method isn't really necessary ... There has to be a way to execute the draw routine when the class is inited or loaded, so the resulting code would be:

var imgBtn:ImageButton = new ImageButton();
imgBtn.BmpNormal = new onstageBMPData(0,0);
this.addChild(imgBtn);

We tried using the INIT, ADDED or RENDER events, but that doesn't seem to work

    public function ImageButton()
    {
        this.addEventListener(Event.RENDER, onAdded, false, 0, false );
    }
+1  A: 

Try Event.ADDED_TO_STAGE and Event.REMOVED_FROM_STAGE to get notified when you are added or removed to the stage display list.

You can listen to this events in the ImageButton instance itself.

public function ImageButton() {
    addEventListener(Event.ADDED_TO_STAGE,handleAdded);
    addEventListener(Event.REMOVED_FROM_STAGE,handleRemoved);
}

private function handleAdded(e:Event):void {
}

private function handleRemoved(e:Event):void {
}
Juan Pablo Califano
This is what I was searching for, thanks.
Run CMD
+1  A: 

You can add the Draw() method in your setter:

 public function set BmpNormal(value:BitmapData):void {  
     bmpNormal = value; 
     Draw();
   }

 private function Draw()
 {
    var bm:Bitmap = new Bitmap(bmpNormal); 
    this.addChild(bm);
 }

Since the bitmapData value is passed in your setter's arguments, you don't need an Event to call the Draw() method, the variable bmpNormal gets its value from the setter , then it can be used in the Draw() function to create a new Bitmap instance that can then be added to the ImageButton.

PatrickS