0
votes

I tried to achieve the following but failed with the code below:

  1. Click mouse once to appear the box.
  2. Click it again to disappear the box.

What happened is that when I fire the mouse.click event (by clicking), that triggered the "stage.addEventListener(MouseEvent.CLICK, boxGone)" event listener as well. At the screen there is nothing happened because I technically addChild and removeChild the box at the same frame.

I am guessing my initial click created and triggered the event listener at the same time.Is there anyway to avoid this from happening without changing my triggering event(mouse click)? below is the code:

public function ClassConstructor(){
 addEventListener(MouseEvent.CLICK, onMouseClickHandler);
}

private function onMouseClickHandler(e:MouseEvent):void{

 box.x = stage.mouseX;
 box.y = stage.mouseY;
 box.gotoAndPlay(1);

 stage.addChild(box);
 stage.addEventListener(MouseEvent.CLICK, boxGone);

}

private function boxGone(e:MouseEvent):void{
 stage.removeChild(box);
 stage.removeEventListener(MouseEvent.CLICK, boxGone);
}

Thanks in advance, Sunny

1

1 Answers

1
votes

Modify your first listener with:

stage.addEventListener(MouseEvent.CLICK, onMouseClickHandler);

The event goes from your main class to the stage, and you add the second listener in between, so it is called just after the function's closure. Another solution, to be sure, would be to call

e.stopImmediatePropagation();

This prevents any listener to catch the same event.