2010-03-21 30 views
1

我有两个类。第一个(起始类):在Actionscript中侦听子对象中的事件的问题

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没有任何反应。有什么问题?

+0

如果设置在onKeyboard一个断点,它被触发? – Robusto 2010-03-21 20:24:51

+0

如果你在onKeyboard中放置了一条trace语句,它是否会写入输出面板? – jessegavin 2010-03-21 20:38:17

+0

关于事件监听器的一件事要注意:它们被强烈引用。如果GC持有事件监听器的对象(在这种情况下,“Well”对象,监听器将会持续存在,导致内存泄漏。有时候需要使用强类型(我注意到在打开/关闭对话框w /事件监听器),但如果可以的话,尝试使用这个:'addEventListener(, ,false,0,true);'这保留了“useCapture”和“priority”的默认值, useWeakReference“属性设置为”true“,当”Well“为GC'd时,事件监听器也将为 – bedwyr 2010-03-22 03:09:34

回答

1

或者作为替代;将事件侦听器添加到舞台,所以它不依赖于具有焦点的井。

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 
     } 
    } 
} 
+0

工作!Thanx – 2010-03-22 10:24:18

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; 
     } 
    } 

}