2009-08-17 43 views
0

我正在研究一個應用程序,並且正在爲它構建一個「鍵盤」組件。鍵盤上有30個按鍵,並且爲每個按鈕創建一個事件處理程序似乎沒有實際意義。點擊按鈕時,其標籤應發送至將其添加到文本輸入字段的功能。鍵盤應用程序 - 有多個按鈕添加信件到textinput的最佳方法?使用事件處理程序?

我應該爲每個按鈕創建一個「click = SomeFunction(Button.label)」,還是有更好/更快/更少的處理器密集型方法來做到這一點?

回答

3

有一個更簡單的方法。您可以擴展按鈕組件並創建一個默認點擊,即使這個點擊起來。然後您可以讓父組件監聽事件。下面是一個簡單的例子:

myButton.mxml:

<?xml version="1.0" encoding="utf-8"?> 
<mx:Button xmlns:mx="http://www.adobe.com/2006/mxml" 
    click="clickKeyHandler(event);"> 

    <mx:Metadata> 

     [Event(name="keyboardClickEvent", type="com.KeyboardEvent")] 
    </mx:Metadata> 

    <mx:Script> 
     <![CDATA[ 

      import com.KeyboardEvent; 

      protected function clickKeyHandler(event:MouseEvent):void{ 


       dispatchEvent(new KeyboardEvent(this.label)); 
      } 
     ]]> 
    </mx:Script> 
</mx:Button> 

com.KeyboardEvent:在應用

package com 
{ 
    import flash.events.Event; 

public class KeyboardEvent extends Event 
{ 

    public static const KEYBOARD_CLICK_EVENT:String = "keyboardClickEvent"; 

    private var _value:String; 

    public function get value():String{ 

     return _value; 

    } 
    public function KeyboardEvent(value:String = "") 
    { 

     super(KEYBOARD_CLICK_EVENT, true); 

     _value = value; 
    } 


    override public function clone() : Event { 
     return new KeyboardEvent(_value); 
    } 

    } 

} 

用法:

<?xml version="1.0" encoding="utf-8"?> 
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
    layout="absolute" creationComplete="initApp();" xmlns:local="*"> 


    <mx:Script> 
     <![CDATA[ 

      import com.KeyboardEvent; 

      private function initApp():void{ 


       this.addEventListener(KeyboardEvent.KEYBOARD_CLICK_EVENT, keyboardHandler); 

      } 


      private function keyboardHandler(event:KeyboardEvent):void{ 

       trace(event.value); 
      } 
     ]]> 
    </mx:Script> 

    <local:myButton label="1" /> 
    <local:myButton label="2" /> 
    <local:myButton label="3" /> 
    <local:myButton label="4" /> 
</mx:Application> 
+0

是線「返回新CompactReportEvent( _value);「 應該說「return new keyboardEvent(_value);」代替? – Seidleroni 2009-08-18 13:31:27

+0

opps是。對不起,我複製了一個粘貼,並錯過了1 – Shua 2009-08-18 13:44:18

+0

我經過並修復了這個例子。 – Shua 2009-08-18 14:03:33

相關問題