动态使用addEventListener?

时间:2010-01-08 14:41:58

标签: actionscript-3

我在flash中创建了一个导航栏,其中包含5个不同的动画片段,用作按钮。每个动画片段(按钮)都有不同的实例名称。有没有办法使用addeventlistener,所以我不必像这样做:

//for button1
 button1.buttonMode = true;// Show the hand cursor
button1.addEventListener(MouseEvent.ROLL_OVER, button1_over);
button1.addEventListener(MouseEvent.ROLL_OUT, button1_out);
button1.addEventListener(MouseEvent.CLICK, button1_click);

function button1_over(e:MouseEvent):void
{
    e.currentTarget.gotoAndPlay("over");
}

function button1_out(e:MouseEvent):void
{
    e.currentTarget.gotoAndPlay("out");
}

function button1_click(e:MouseEvent):void
{
    var request:URLRequest = new URLRequest("http://website.com");
    navigateToURL(request);
}
//for button2
button2.buttonMode = true;// Show the hand cursor
    button2.addEventListener(MouseEvent.ROLL_OVER, button2_over);
    button2.addEventListener(MouseEvent.ROLL_OUT, button2_out);
    button2.addEventListener(MouseEvent.CLICK, button2_click);

    function button2_over(e:MouseEvent):void
    {
        e.currentTarget.gotoAndPlay("over");
    }

    function button2_out(e:MouseEvent):void
    {
        e.currentTarget.gotoAndPlay("out");
    }

    function button2_click(e:MouseEvent):void
    {
        var request:URLRequest = new URLRequest("http://website.com");
        navigateToURL(request);
    }

......等所有五个按钮?

1 个答案:

答案 0 :(得分:5)

function buttonOver( e:MouseEvent ):void {
  e.currentTarget.gotoAndPlay('over');
}
... etc

for each( var b:MovieClip in [button1,button2,button3,button4,button5] ) {
  b.addEventListener( MouseEvent.ROLL_OVER, buttonOver );
  b.addEventListener( MouseEvent.ROLL_OUT, buttonOut );
  b.addEventListener( MouseEvent.CLICK, buttonClick );
}

你甚至可以通过收集函数内部的事件类型来进一步改进它,只需要有一个:

function buttonHandler( e:MouseEvent ):void {
  // see the docs for MouseEvent and figure
  // out what string to pass to goToAndPlay
}