如何从一个类分派事件并在不是第一个类的子类或父类的另一个类中侦听该事件?
我正在使用 AS3 制作游戏。我有三个类(Spaceship、UFO 和 Scoreboard),它们都是 GameEngine 类的子类。
我想将 eventListener 放入 Scoreboard 中,然后从 Spaceship 和 UFO 发送调度事件来更新 scoreboard 实例。
由于 Spaceship 和 UFO 既不是 Scoreboard 的父级也不是子级,因此向dispatchEvent 添加 bubbling=true 参数不会执行任何操作。
如何让 Scoreboard 监听 *dispatchEvent*s,而不执行以下操作:
GameEngine.scoreboard.dispatchEvent(new Event("shipWasHit", true)); 。
这样做似乎很愚蠢 为什么我要使用dispatchEvent——为什么不直接调用该函数呢?如果我希望其他类监听同一个调度事件怎么办?
请指教。
I am making a game using AS3. I have three classes (Spaceship, UFO, and Scoreboard) which are all children of the class GameEngine.
I want to put eventListeners in Scoreboard and then send dispatchEvents from Spaceship and UFO to update the scoreboard instance.
Since Spaceship and UFO are neither parents or children of Scoreboard, adding a bubbling=true parameter to the dispatchEvent does nothing.
How do I get Scoreboard to listen for *dispatchEvent*s without doing this:
GameEngine.scoreboard.dispatchEvent(new Event("shipWasHit", true));
This seems silly to do it this way. Why would I use a dispatchEvent at all -- why not call the function directly? And what if I want other classes to listen for the same dispatchEvent?
Please advise.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
查看观察者模式。这是一个很好的链接:
Check out the Observer pattern. Here's a good link:
http://www.swinburne.edu.au/design/tutorials/P-flash/T-The-Observer-Design-Pattern-in-Actionscript-3/ID-145/
由于任何使用捕获阶段或冒泡阶段且传播不会中断的事件都会在阶段中运行,因此您只需在指定类内为阶段添加侦听器即可。
示例代码:
现在,这里有一些注意事项。首先,需要实例化此类并将其添加到舞台中才能引用舞台。否则,您需要将阶段作为参数传递,并且在某些情况下可能返回 null。最后,您必须在分派事件之前实例化它,尽管这对于我现在看到的代码来说似乎不是问题。
Since any event that uses either the capture phase or bubble phase that doesn't have its propagation interrupted runs through the stage, you can just add a listener for the stage inside of the specified class.
Example code:
Now, there are a few caveats here. First off, this class needs to be instantiated and added to the stage in order to reference the stage. Otherwise, you'll need to pass in the stage as a parameter, and that can return null in cases. Finally, you'll have to instantiate this before the event is dispatched, though this doesn't seem to be a problem with the code I'm seeing right now.
我使用这个解决方案(已发布在所以)
i use this solution (already posted on SO)
你的宇宙飞船和 UFO 会这样做:
并且你的记分板需要知道要监听哪些宇宙飞船和 UFO 的事件:
并且
添加这些侦听器的好地方是在创建这些宇宙飞船和 UFO 的类中,或者在记分板本身中如果在某个时候你告诉它要听哪些船只和不明飞行物。
Your Spaceships and UFO's would do this:
and your Scoreboard would need to know which spaceships and UFO's to listen to for those events:
and
A good place to add those listeners is in the class that creates those Spaceships and UFO's, or in the Scoreboard itself if at some point you tell it what ships and UFO's to listen to.