【问题标题】:Node.js: Function vs EventEmitterNode.js:函数与 EventEmitter
【发布时间】: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 中,他使用EventEmitterFunction 实现了他的示例。 execution 没有区别,只是事件被分配给一个对象(称为 student_max),如果要为另一个学生实现,事件必须重写(即重复)但在功能上所有对象(所有学生) 可以使用 score 方法。

谁能通过示例和代码清楚地解释何时使用EventEmitter,何时使用Function

【问题讨论】:

标签: node.js events eventemitter


【解决方案1】:

最好最清晰的答案在这个linkTHIS
一般来说,我们应该看Clean Code的事件,Open/Closed原理(解耦)是SOLID原理之一。

【讨论】:

    猜你喜欢
    • 2012-05-03
    • 2013-04-08
    • 2012-12-17
    • 2021-10-26
    • 2012-02-12
    • 2014-10-09
    • 2015-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多