AS3 - Button inside MovieClip triggers MC's ev

2019-02-27 10:31发布

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.

2条回答
别忘想泡老子
2楼-- · 2019-02-27 10:38

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.

查看更多
【Aperson】
3楼-- · 2019-02-27 10:58

If you add button in a MC, and you click on the button, you also click on the MC, because the part of the MC that is under the button is still there and it runes the function for the whole of the MC, you can't remove it.

So it's good idea to make a function that will check if the button is pressed, otherwise it will run the function for the whole of the MC.

This one should do it.

//add this in you constructor

mc.addEventListener(MouseEvent.MOUSE_DOWN, myReleaseFunc);
function myReleaseFunc(e:MouseEvent):void {
    if(e.currentTarget.name == Btn1) //Btn1 is instance name for a button
    {
         Btn_func1();
    }
    else if(e.currentTarget.name == Btn2) //Btn2 is another button.
    {
         Btn_func2();
         //For every button you'll need to add another function and if statement to check if that button was clicked.
    }
    else
    {
         Mc_func();
    }

} 

// this outside the main class

function Mc_func():void{
    //you code here
}
function Btn_func1():void{
    //you code here
}
function Btn_func2():void{
    //you code here
}

I think that this way is much more effiecient and it will works better and faster and you'll have a lot smaller chance of overloading the system.

查看更多
登录 后发表回答