【发布时间】:2021-12-30 17:05:58
【问题描述】:
在topic关于EventEmitter,有人说在下面的例子中,不需要使用事件。毫无意义:
const events = require("events")
const eventEmitter = new events.EventEmitter()
eventEmitter.on("say_hi", () => {console.log("sa")})
eventEmitter.emit("say_hi")
他说过:
When you build a library or internal API, it allows other parts of your code (or people using your code) to subscribe to events without you needing to know this in advance.
For the case you used it above, it does not make sense.
但我完全没看懂他这句话的意思。
我完全不知道什么时候用EventEmitter,什么时候用Function。
在另一个topic 中,他使用EventEmitter 和Function 实现了他的示例。 execution 没有区别,只是事件被分配给一个对象(称为 student_max),如果要为另一个学生实现,事件必须重写(即重复)但在功能上所有对象(所有学生) 可以使用 score 方法。
谁能通过示例和代码清楚地解释何时使用EventEmitter,何时使用Function?
【问题讨论】:
-
Related: en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern 对于大型应用程序 IMO 更有用。对于较小的,至少根据我的经验,传递的普通函数工作得很好。
标签: node.js events eventemitter