nix
nix

Reputation: 2285

Why KeyboardEvent listener (AS3) does not react until I add it to the stage?

Why KeyboardEvent listener (AS3) does not react until I add it to the stage and not when I simply write it down in the Document Class just like I do with any other function? I mean, I have to write

stage.addEventListener(KeyboardEvent.KEY_DOWN, someFunc);

and not simply

addEventListener(KeyboardEvent.KEY_DOWN, someFunc);

just like I do with the others?

Upvotes: 0

Views: 696

Answers (2)

Tristan Verheecke
Tristan Verheecke

Reputation: 1

I had this problem with Flashbuilder 4.6 utilizing Flex and Actionscript3. I'm just posting this in case some other people wanted an alternative to the solution, because this solution did not work for me.

This is what I did:

public class CoreContainer extends Canvas implements IFocusManagerContainer, IFocusManagerComponent
{
    private var _focus:FocusManager = new FocusManager(this as IFocusManagerContainer);

    public function CoreContainer()
    {
        ...
        this._focus.setFocus(this);
        this.addEventListener(KeyboardEvent.KEY_DOWN, this.handleKeyDown);
        ...
    }

    private function handleKeyDown(event:KeyboardEvent):void
    {
        KeyboardShortcuts.handleKeyDown(event);
    }
}

Basically I did the same thing as a--m, but since I couldn't access stage as a global variable in flex I improvised so I could access it for this specific class.

Upvotes: 0

a--m
a--m

Reputation: 4782

you actually can... but before you need to define the stage.focus to the object you want to listen to the KeyboardEvent.KEY_DOWN event.

stage.focus = this
this.addEventListener(KeyboardEvent.KEY_DOWN, someFunc);

In the as3 reference guide you can see more info about the KeyboardEvent:

To listen globally for key events, listen on the Stage for the capture and target or bubble phase.

This is quite useful if you want to listen the KeyboardEvent on a TextField for example:

text_tf.addEventListener(KeyboardEvent.KEY_DOWN, someFunc);

Hope this clarifies your doubt.

Upvotes: 2

Related Questions