views:

172

answers:

2

How to check if sth alr exist on stage? Shldn't it print out "doesn't exist" for the 1st one and "exist" for the second one? But it prints out "doesn't exist" for both.

I added a timer cos I thought need to wait for a while for it to add to the stage, but it doesn't work.

var idonnoe:TextField = new TextField();

if (Boolean(this.getChildByName('idonnoe'))) 
  {
     trace("exists");
  }
  if (!Boolean(this.getChildByName('idonnoe'))) 
  {
     trace("doesn't exist");
}

addChild(idonnoe);
idonnoe.text = "hello";

var delay1:Timer = new Timer(1000, 1);
delay1.start();
delay1.addEventListener(TimerEvent.TIMER_COMPLETE, afterDelay);

function afterDelay(e:TimerEvent) :void {
    if (Boolean(this.getChildByName('idonnoe'))) 
      {
         trace("exists");
      }
      if (!Boolean(this.getChildByName('idonnoe'))) 
      {
         trace("doesn't exist");
    }
}
+1  A: 

The getChildByName method takes into consideration the myDisplayObject.name property, not the name of the variable that points to it. Try setting the property and it should now exist the way you are searching for it.

idonnoe.name = "idonnoe";
LopSae
The delay you have should not even be necesary anymore.
LopSae
A: 

It's more common to reference your objects directly. This makes it easier to handle this kind of cases. The DisplayObjectContainer's 'contains(displayObject:DisplayObject)' method is really handy to find out wheter an object is attached or not to the display list.

var displayObject:TextField = new TextField(); // any sublclass of DisplayObject
addChild(displayObject);

// test if the current display list contains the sprite
trace( contains(displayObject) );

// test if the sprite is attached to the stage
trace( displayObject.stage != null );

// test if the sprite is attached to ANY display list
trace (displayObject.parent != null );
Theo.T
When would u use a Sprite? What I know of Sprite is a Movie Clip without timeline.
yeeen
oh sorry, I just used a sprite but it could have been a TextField, MovieClip or anything else really extending DisplayObject. will edit ...
Theo.T
And to answer your question quickly, sprite is a 'lighter' DisplayObject since it doesn't contain timeline related methods. Also the sprite is not a dynamic class so you cannot create fields on the fly (which makes the execution slower). Basically, try to use Sprite rather than MovieClip if your DisplayObject doesn't contain any timeline.
Theo.T