I found something strange while I was coding today. I couldnot find explenation of what happend to me today.
I have created button and addEventListener to it.
private function drawButtons():void{
survivorModeBtn = new SurvivorModeBtn();
trace("I registered Event Listener with button here");
survivorModeBtn.addEventListener(MouseEvent.CLICK,onSurvivorModeBtnClick);
addChild(survivorModeBtn);
}
private function onSurvivorModeBtnClick(e:MouseEvent):void{
trace("I clicked on btn here");
//I will dispatch event here which runs second part of code
mainMenuViewEvent = new MainMenuViewEvent("onSurvivorModeIsClicked");
hideButtons();
dispatchEvent(mainMenuViewEvent);
}
Dispatched event will run those parts of code:
public function createClickToStart():void{
trace("here I register event listener MouseEvent.Click");
stage.addEventListener(MouseEvent.CLICK,onClick);
}
private function onClick(e:MouseEvent):void{
trace("onClick()");
}
When I run my program and Click on first button. I got this output in console:
I registered Event Listener with button here
I clicked on btn here
here I register event listener MouseEvent.Click
onClick()
I can t understand how can I see “onClick()” msg, if I clicked just on first button, and even in that time was not stage redistered with CLICK event.
Thank you for solution to my problem.
You have experienced what is called “bubbling” of an event. First, the “click” event is dispatched to the topmost object under cursor, then it raised upwards via parent references all the way to stage, if you don’t force it to
e.stopPropagation(). So, while the event was being parsed withinsurvivorModeBtn, it has not yet reached stage, an in the meantime you ssign stage listener for this type of events. Then it bubbles up and hits stage, stage says “Wow, I have a MouseEvent.CLICK listener registered, let’s call it right now!” and callsonClick()function, making you receive your last trace result.