Question

I am newbie to actionscript. Just started learning it a couple of days ago. I am trying to add keyboardevents for a particular button. Here is what I have done so far.

import flash.events.KeyboardEvent;
public function f1():void
{
     // something
}
public function keyBoardListener(keyEvent:KeyboardEvent):void
{
    if(keyEvent.keyCode==37)
        f1();

}

and in the button

<Lib:ManagedButton
     id = "MB"
     labelText = "MB"
     image = " ... "
     click="f1()"
     enabled = "false"
     stage.addEventListener(KeyboardEvent.KEY_DOWN,keyBoardListener);
 />

This is the error I am getting:

Attribute name "stage.addEventListener" associated with an element type "Lib:ManagedButton" must be followed by the ' = ' character.    

What I am trying to do is call the function f1() on pressing the left arrow key. I do not want this to happen for all the buttons on this page but only this button.

Was it helpful?

Solution

You're issue is the following:

stage.addEventListener(KeyboardEvent.KEY_DOWN,keyBoardListener);

You have that in the markup as a property (it's expecting param="value") and you're trying to call a code function.

You should create a class file for your button and add the listener and handler there. That way it will only run when the button has focus (which is what I'm assuming you want here).

package Lib {
    public class MyButton extends ManagedButton {
        public function MyButton(){
            this.addEventListener(Event.ADDED_TO_STAGE,addedToStage,false,0,true);
            this.addEventListener(Event.REMOVED_FROM_STAGE,removedFromStage,false,0,true);
            this.addEventListener(MouseEvent.CLICK,clickEventHandler,false,0,true);
        }

        private function addedToStage(e:Event):void {
            this.addEventListener(KeyboardEvent.KEY_DOWN, keyBoardListener,false,0,true);
        }
        private function removedFromStage(e:Event):void {
            this.removeEventListener(KeyboardEvent.KEY_DOWN, keyBoardListener,false);
        }

        [Bindable]
        public var clickHandler:Function;

        private function clickEventHandler(e:Event):void {
            if(clickHandler != null) clickHandler();
        }
        public function keyBoardListener(keyEvent:KeyboardEvent):void
        {
            if(keyEvent.keyCode==37)
               if(clickHandler != null) clickHandler();
        }
    }
}

Then you could just specify the value for clickHandler and have both your keyboard and click events launch it. I don't really use FLEX, so someone may need to correct this, but I think this is what it would look like:

<Lib:MyButton
     id = "MB"
     labelText = "MB"
     image = " ... "
     enabled = "false"
     clickHandler = "f1()"
 />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top