Search code examples
actionscript-3eventskeyboardstage

ActionScript - Keyboard Events Without Stage?


is it true that keyboard events can not be accessed outside of the stage on non display objects?

example:

package
{
//Imports
import flash.events.EventDispatcher;
import flash.events.KeyboardEvent;

//Class
public class TestClass extends EventDispatcher
    {
    //Constructor
    public function TestClass()
        {
        init();
        }

    //Initialization
    public function init():void
        {
        addEventListener(KeyboardEvent.KEY_UP, keyUpEventHandler);
        }

    //Key Up Event Handler
    private function keyUpEventHandler(evt:KeyboardEvent):void
        {
        trace("Test Class:  " + evt.keyCode);
        }
    }
}

here i would like to initialize a new TestClass() then press a on the keyboard to receive the output Test Class: a.


Solution

  • To my knowledge (and according to the livedocs example) you need to add a KeyboardEvent listener to a displayObject. I've done this in abstract and static classes by passing a reference to the stage (or any displayObject) to your class's init method or constructor.

    So, for example, in your document class, you could do:

    var testClass:TestClass = new TestClass();
    testClass.init(stage);
    

    and in TestClass.as do:

    public function init(stageReference:DisplayObject):void
    {
       stageReference.addEventListener(KeyboardEvent.KEY_UP, keyUpEventHandler);
    }
    

    While I agree it's a little wonky, I don't think there's a way to do it without using a DisplayObject.