如何为观察者系统创建这种接口?
addListener[FooEvent] { e => println("Got a FooEvent") }
dispatchEvent(new FooEvent())
这可能吗?我需要能够将 addListener 方法中的类型参数转换为字符串并将侦听器存储在映射(eventtype -> 函数)或其他内容中。然后,对于dispatchEvent,我需要确定参数的字符串类型以检索该事件的侦听器。
我不确定实现,但我真的很想使用这种接口,而不必为可观察对象上的每个事件类型声明 2 个方法。有什么想法吗?
addListener[FooEvent] { e => println("Got a FooEvent") }
dispatchEvent(new FooEvent())
Is this even possible? I'd need to be able to convert the type parameter in the addListener
method to a string and store the listeners in a map (eventtype -> function) or something. Then for dispatchEvent
I'd need to determine the string type for the parameter to retrieve the listeners for that event.
I'm unsure of the implementation but I'd really like to use this kind of interface instead of having to declare 2 methods for each event type on an observable object. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,这是可能的,而且非常简单。但您必须记住,如果您想再次从侦听器中将其删除,则需要保留传入函数的引用。您可以做的是这样的:
addListener
返回函数,以便您可以将其存储在val
中以便稍后删除:如果您想将事件类型作为类型提供参数,您必须另外采用隐式
Manifest
或ClassManifest
参数:并使用它:
Yes it is possible and quite straight forward. You have to remember though, that you need to hold on to the reference of a function you pass in if you want to remove it from the listeners again. What you could do is something like this:
addListener
returns the function so you can store it inval
for removing it later:If you want to supply the event type as a type parameter you have to additionally take an implicit
Manifest
orClassManifest
parameter:And using it: