2013-06-12 343 views
0

假設我想創建一個按鈕。這應該很容易 - 只需創建一個正方形,的addChild將其添加到屏幕上的事件偵聽器mouse.CLICK事件動態添加事件偵聽器

add_btn_listeners():void 
{ 

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

假設,雖然你想創建20個按鈕。然後,您需要使用與上述btn_clc1函數類似的20個函數,並使用事件偵聽器進行適當的單擊。

但是,假設你想要的行動非常輕微,如索引。例如,在同一個監聽器btn_clc1偵聽器中,btn [0]調用action1,btn [1]調用action2等。

一個很常見的例子就是鼠標滾動。在翻轉以突出顯示正方形時,增加alpha圖層以突出顯示菜單選擇。突出顯示的圖層將取決於索引,如下所示:btn [index] .alpha = .9;

有沒有辦法在這種情況下減少事件監聽器的數量或更優化的代碼?我看過的大多數例子對大案例來說似乎都很淺薄。

回答

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); 
} 
1

你可以做的一件事是在事件處理程序中的事件對象內有一個'target'屬性。這是指派發事件的對象。您可以將它重新轉換爲您分配給事件偵聽器並訪問該事件的任何內容,或者只需使用循環/ 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);