【发布时间】:2014-01-03 09:26:51
【问题描述】:
我是 AS3/Flash 的新手,正在学习事件处理。我有一个分派事件的“Bell”类,如果我将事件侦听器添加到该 Bell 类的实例,它工作正常。不过,这不是我想要的。我还有另一门课,宠物,我想听贝尔。我看到了铃铛的痕迹,但没有看到宠物的痕迹。
这是铃铛的代码:
public class Bell extends EventDispatcher {
public static const BELL_RING:String = "bellRing";
public static const RING_INTERVAL:int = 1500;
private var ringIntervalID:int;
public function Bell()
{
ringIntervalID = setInterval(ringBell,RING_INTERVAL);
}
public function ringBell():void {
trace("RINGING THE BELL");
dispatchEvent(new Event(Bell.BELL_RING));
}
}
...对于宠物:
public class VirtualPet {
private var senseOfHearing:EventDispatcher = new EventDispatcher();
public function Pet(name:String):void
{
senseOfHearing.addEventListener(Bell.BELL_RING,heardBell);
}
public function heardBell(e:Event):void {
trace("Pet hears bell ringing");
}
}
...对于主类:
public class VirtualZoo extends Sprite
{
public function VirtualZoo()
{
var bell:Bell = new Bell();
var pet:VirtualPet = new VirtualPet('Stan');
}
}
非常感谢任何帮助!事件已正确导入,没有编译器错误。
【问题讨论】:
-
这两个类是如何联系起来的?
-
对不起,我更新了,把主类加到最后了。
-
如果你想让铃铛响应宠物,你必须将一个对铃铛对象的引用传递给宠物,这样宠物就可以为它注册一个监听器并在何时响应需要。
-
事件监听器需要添加到派发事件的类实例中。在您的情况下,
Bell调度事件,但事件侦听器被添加到EventDispatcher的实例中。
标签: actionscript-3 flash