flashactionscript-3flash-cs4

How to check if something already exist on the Flash stage?


How to check if something already exist on stage? Shouldn'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 because 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");
    }
}

Solution

  • 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";