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.getChildByNa开发者_StackOverflow社区me('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");
}
}
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";
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 );
精彩评论