事件应该自行触发吗?
我不是一个可靠的 GUI 程序员,所以我试图理解不同的事件架构。我正在开发一个系统(在 GWT 中,但我不确定这是否重要),我们将在其中引入一些自定义事件。一般来说,创建事件并将事件自身触发到事件总线上是一种好的做法吗?
根据在线的一些文章和教程,我们的控制器代码实际上触发了事件,但是每个控制器都必须复制代码来触发自定义事件。看来,如果您只是在事件本身上放置一个 fire()
方法,您就可以避免这种重复。
这样做的优点/缺点是什么?
I'm not a solid GUI programmer, so I'm trying to understand different event architectures. I'm developing a system (in GWT, but I'm not sure that matters) where we are introducing a few custom events. In general, is it good practice to create an event and have the event fire itself onto to the event bus?
Following some articles and tutorials online, we have our controller code actually firing the events, but then each controller has to duplicate the code to fire the custom event. It seems that if you just put a fire()
method on the event itself you can avoid that duplication.
What are the pros/cons of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为了让事件自行触发,您需要在创建事件时将 EventBus 实例注入到事件中。这意味着您的控制器(更新事件的控制器)将具有:
如果您像这样重新编写代码:
那么您不必将任何逻辑或对服务的引用放入您的事件实例中,因为实际上并不需要它。如果您使用的是 GWT,则
HandlerManager
类已经为您实现了事件总线。In order to have an event fire itself, you'd need to inject the EventBus instance into the event when you create it. This means your controller (the one newing up the event) would have:
If you rework the code like this:
then you wouldn't have to put any logic or references to services inside your Event instance, where it's not really needed. If you're using GWT, the
HandlerManager
class already implements an event bus for you.