在Actionscript中侦听子对象中的事件的问题

时间:2010-03-21 19:57:27

标签: flex flash actionscript-3

我有两节课。第一个(起始类):

package
{
 import flash.display.Sprite;
 import flash.events.KeyboardEvent;
 import tetris.*;

 public class TetrisGame extends Sprite
 {

  private var _gameWell:Well;

  public function TetrisGame()
  {    
   _gameWell = new Well();
   addChild(_gameWell);
  } 
 }
}

第二个:

package tetris
{
 import flash.display.Sprite;
 import flash.events.KeyboardEvent;

 public class Well extends Sprite
 {

  public function Well()
  {
   super();

   addEventListener(KeyboardEvent.KEY_DOWN, onKeyboard);
  }

  private function onKeyboard(event:KeyboardEvent):void
  {
   //some code is here
  }


 }
}

但是当我按下键盘上的任何按钮时,子类Well没有任何反应。有什么问题?

2 个答案:

答案 0 :(得分:2)

好的,我懂了! =))

我应该专注于子精灵,以便它可以监听键盘事件。

package
{
    import flash.display.Sprite;
    import flash.events.KeyboardEvent;
    import tetris.*;

    public class TetrisGame extends Sprite
    {

        private var _gameWell:Well;

        public function TetrisGame()
        {    
            _gameWell = new Well();
            addChild(_gameWell);

            stage.focus = _gameWell;
        } 
    }

}

答案 1 :(得分:1)

或作为替代;将事件监听器添加到阶段,因此它不依赖于Well具有焦点。

package tetris
{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.KeyboardEvent;

    public class Well extends Sprite 
    {

        public function Well():void 
        {
            super();

            if (stage) init();
            else addEventListener(Event.ADDED_TO_STAGE, init);
        }

        private function init(e:Event = null):void 
        {
            removeEventListener(Event.ADDED_TO_STAGE, init);
            stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyboard);
        }

        private function onKeyboard(event:KeyboardEvent):void
        {
            //some code is here
        }
    }
}