我可以将按钮传递给自己的MouseEvent函数吗?

时间:2014-03-22 04:54:49

标签: actionscript-3 flash movieclip

我有多个使用Flash发布到FlashDevelop中的MovieClip符号(在我的示例中我只使用2)。每个都有3帧默认,悬停和点击,我用作按钮。

private var btnPlay:PlayButton, btnQuit:QuitButton;

btnPlay = new PlayButton();
btnQuit = new QuitButton();

btnPlay.addEventListener(MouseEvent.ROLL_OVER, onRollOverHandler);
btnPlay.addEventListener(MouseEvent.ROLL_OUT, onRollOutHandler);
btnPlay.addEventListener(MouseEvent.MOUSE_DOWN, onPressHandler);
btnPlay.addEventListener(MouseEvent.MOUSE_UP, onReleaseHandler);

btnPlay.buttonMode = true;
btnPlay.useHandCursor = true;

function onRollOverHandler(myEvent:MouseEvent):void {
    btnPlay.gotoAndStop(2);
}

function onRollOutHandler(myEvent:MouseEvent):void {
    btnPlay.gotoAndStop(1);
}

function onPressHandler(myEvent:MouseEvent):void {
    btnPlay.gotoAndStop(3);
}

function onReleaseHandler(myEvent:MouseEvent):void {
    btnPlay.gotoAndStop(2);
}

// Same code for btnQuit here, but replace btnPlay with btnQuit

有没有一种方法可以将按钮本身传递给MouseEvent函数,而不是向每个按钮添加新的EventListener,这些按钮实际上与我上面做的事情完全相同。 (我意识到这可能很难,因为所有按钮都是他们自己的类)

btnPlay.addEventListener(MouseEvent.ROLL_OVER, onRollOverHandler(btnPlay));
btnPlay.addEventListener(MouseEvent.ROLL_OUT, onRollOutHandler(btnPlay));
btnPlay.addEventListener(MouseEvent.MOUSE_DOWN, onPressHandler(btnPlay));
btnPlay.addEventListener(MouseEvent.MOUSE_UP, onReleaseHandler(btnPlay));

function onRollOverHandler(myEvent:MouseEvent, inButton:MovieClip):void {
    inButton.gotoAndStop(2);
}

function onRollOutHandler(myEvent:MouseEvent, inButton:MovieClip):void {
    inButton.gotoAndStop(1);
}

function onPressHandler(myEvent:MouseEvent, inButton:MovieClip):void {
    inButton.gotoAndStop(3);
}

function onReleaseHandler(myEvent:MouseEvent, inButton:MovieClip):void {
    inButton.gotoAndStop(2);
}

2 个答案:

答案 0 :(得分:1)

也许我是误会,但是" event.target"为您提供已单击按钮的参考。因此,如果您想对点击的按钮执行某些操作,请写下:

myEvent.target.gotoAndStop(1);

或者有时您可能需要使用" currentTarget"。您仍然需要为每个函数创建侦听器,但可以使用一组处理程序。

答案 1 :(得分:0)

简单回答:不会。你可能会遇到一些麻烦来覆盖MouseEvent类并允许它发送其他参数,但为什么在这种情况下呢?你似乎没有保存任何代码。

轻微更新:

这是对原始代码的可能有用的简化。它节省了几行代码并只使用了一个处理函数。显然,'trace'语句可以被各种'gotoAndStop()'语句取代:

btnPlay.addEventListener(MouseEvent.ROLL_OVER, HandleAll);
btnPlay.addEventListener(MouseEvent.ROLL_OUT, HandleAll);
btnPlay.addEventListener(MouseEvent.MOUSE_DOWN, HandleAll);
btnPlay.addEventListener(MouseEvent.MOUSE_UP, HandleAll);

function HandleAll(e)
{
    if (e.type == "rollOver")  trace("rollover");
    if (e.type == "rollOut")   trace("rollout");
    if (e.type == "mouseDown") trace("mousedown");
    if (e.type == "mouseUp")   trace("mouseup");
}