Search code examples
actionscript-3buttonmouseeventmovieclip

AS3 - Button inside MovieClip triggers MC's event


On stage, I have a MovieClip named "mc" with a simple rectangle drawn inside. mc also has a Button child named "btn" which is another simple rectangle ( smaller than mc's rectangle obviously). Then I have this code on stage.

function mcDown( _e:MouseEvent):void{
    trace( "mc" );
}
function btnClick( _e:MouseEvent):void{
    trace( "btn" );
}
mc.addEventListener( MouseEvent.MOUSE_DOWN, mcDown );
mc.btn.addEventListener( MouseEvent.CLICK, btnClick );

The problem I am having is when click the button, mcDown event is also triggered and traces both "mc" and "btn".

How can I make it so that when I click the button, it triggers only btnClick and not mcDown along? I tried MOUSE_UP instead of CLICK, same problem. And mcDown event has to remain MOUSE_DOWN.


Solution

  • There is no way to prevent bubbling except setting the bubbles parameter as false in the dispatchEvent.

    dispatchEvent(EVENT_TYPE, BUBBLES,....);
    

    However, you can avoid the bubbling by doing a check. Just have the below line as first line of your listener function it avoids the events dispatched from all objects other then targets.

    if(e.eventPhase != EventPhase.AT_TARGET) return;
    

    So, for your sample code, when you click on the button both the events dispatches but in the mcDown function it won't execute after the above said line.