Apache flex 在Actionscript的子对象中侦听事件时出现问题
我有两节课。第一个(起始班): 第二点:Apache flex 在Actionscript的子对象中侦听事件时出现问题,apache-flex,flash,actionscript-3,Apache Flex,Flash,Actionscript 3,我有两节课。第一个(起始班): 第二点: package tetris { import flash.display.Sprite; import flash.events.KeyboardEvent; public class Well extends Sprite { public function Well() { super(); addEventListener(KeyboardEvent.KEY_DOWN, onKeyboard); } p
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
}
}
}
但是当我按下键盘上的任何按钮时,子类没有任何反应。有什么问题吗?好的,我明白了!=)
我应该将焦点设置在子精灵上,以便它可以侦听键盘事件
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;
}
}
}或作为替代方案;将事件监听器添加到舞台,这样它就不依赖于有焦点的井
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
}
}
}
如果在onKeyboard中设置断点,它会被触发吗?如果在onKeyboard中放置跟踪语句,它会被写入输出面板吗?关于事件侦听器,需要注意的一点是:它们是强引用的。如果GC保存事件侦听器的对象(在本例中为“Well”对象,侦听器将持续存在,导致内存泄漏。有时会使用强类型(我注意到在打开/关闭带有事件侦听器的对话框时需要使用强类型),但如果可以,请尝试使用以下命令:
addEventListener(,false,0,true);
这将保留“useCapture”和“priority”的默认值,但会将“useWeakReference”属性设置为“true”。当“Well”为GC时,事件侦听器也将为。
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
}
}
}