R – Keyboard Application – Best way to have multiple buttons add letter to textinput? Use event handlers

actionscriptactionscript-3apache-flexkeyboard

I'm working on an application and I am building a "Keyboard" component for it. There are 30 keys on the keyboard and it doesnt seem to make practical sense to create an event handler for each button. When the button is clicked, its label should be sent out to a function which adds it to a textinput field.

Should I just create a "click=SomeFunction(Button.label)" for each button or is there a better/faster/less processor intensive way to do it?

Best Answer

there is a much easier way. you can extend the button component and create a default click even that bubbles up. You then can have the parent component listening for the event. Here is a quick example:

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

    }

}

usage in app:

<?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>
Related Topic