开发者

ActionScript - Keyboard Events Without Stage?

开发者 https://www.devze.com 2023-03-15 04:48 出处:网络
is it tr开发者_如何学Goue that keyboard events can not be accessed outside of the stage on non display objects?

is it tr开发者_如何学Goue 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号