0

Suppose I want to create a single button. This should be easy enough - just create a square, addChild to add it to the screen and an event listener for mouse.CLICK event

add_btn_listeners():void
 {

   btn[0].addEventListener(MouseEvent.CLICK, btn_clc1);
 }
public function btn_clc1(event:Event):void
 {
   action1();
 }

Suppose though that you wanted to create twenty buttons. You would then need twenty functions similar to the above btn_clc1 function with an event listener for the appropriate click.

But suppose you wanted the action to very slightly such as by index. For example, btn[0] calling action1, btn[1] calling action2, etc. in the same listener btn_clc1 listener.

A very common example of this would be mouse rollover. On rollover to highlight a square for instance, increasing the alpha layer to highlight a menu selection. The highlighted layer would depend on the index, something like: btn[index].alpha = .9;

Is there a way to reduce the number of event listeners, or code more optimally in cases like this? Most of the example's I've seen seem kind of shallow for larger cases.

4

2 回答 2

1

您可以做的一件事是在事件处理程序的事件对象中,有一个“目标”属性。这是指派发事件的对象。您可以将它转换回您分配给事件侦听器的任何内容并访问它,或者可以只使用循环/if 块来比较以确定它是哪个按钮。

import flash.display.Sprite;

var aButton:Sprite = new Sprite();

function clicked(inputEvent:MouseEvent):void {
    var theButton:Sprite = (Sprite) (inputEvent.target);
    trace(theButton); // traces out the sprite

    // can compare
    trace(theButton == aButton); // traces out true

    // if the had any (custom) properties, you could also access them, such as:
    trace(theButton.visible);
}
aButton.addEventListener(MouseEvent.CLICK, clicked, false, 0, true);
于 2013-06-12T01:27:18.110 回答
1

这正是面向对象编程旨在解决的问题类型。只需创建一个包含事件处理程序的类 - 然后您可以创建任意数量的事件处理程序。

类示例:

public class MyButton extends Sprite
{
    public function MyButton()
    {
        graphics.beginFill(0);
        graphics.drawRect(0, 0, 50, 30);
        graphics.endFill();

        addEventListener(MouseEvent.CLICK, _mouse);
        addEventListener(MouseEvent.ROLL_OVER, _mouse);
        addEventListener(MouseEvent.ROLL_OUT, _mouse);
    }

    private function _mouse(e:MouseEvent):void
    {
        switch(e.type)
        {
            case MouseEvent.CLICK:
                trace("click");
            break;

            case MouseEvent.ROLL_OVER:
                alpha = 0.9;
            break;

            case MouseEvent.ROLL_OUT:
                alpha = 1;
            break;
        }
    }
}

然后你可以像这样创建它们:

for(var i:int = 0; i < 5; i++)
{
    var btn:MyButton = new MyButton();

    btn.x = i * 60;
    addChild(btn);
}
于 2013-06-12T02:29:33.223 回答