Reputation: 809
I want to make it when a button is hit it creates a child and then when the child is hit it deletes the child....this works but then when I click the button again the child doesn't get created again.
How can I do this? Here is my code:
var bikeride:MovieClip = new ridingbike();
ridinb.addEventListener(MouseEvent.CLICK, openbike);
function openbike(evt:MouseEvent):void {
addChild(bikeride);
}
bikeride.addEventListener(MouseEvent.CLICK, closebike);
function closebike(evt:MouseEvent):void {
bikeride.removeChildAt(0);
}
Upvotes: 0
Views: 97
Reputation: 39456
Adding to Florent's answer you may want to also remove the event listeners and check if bikeride
has a parent before trying to work with it. This avoids null object reference errors and to ensure that bikeride
gets garbage collected (removed from memory, freeing resources).
bikeride.addEventListener(MouseEvent.CLICK, closebike);
function closebike(evt:MouseEvent):void
{
if(bikeride.parent)
{
bikeride.parent.removeChild(bikeride);
}
bikeride.removeEventListener(MouseEvent.CLICK, closebike);
}
It is really important to remove event listeners if you're expecting your object to get properly 'deleted'.
Upvotes: 1
Reputation: 12420
You can remove the child using:
removeChild(bikeride);;
If you don't store the bikeride
instance you can do this:
function closebike(evt:MouseEvent):void {
var bike:DisplayObject = DisplayObject(evt.target);
bike.parent.removeChild(bike);
}
Upvotes: 2