主流库
https://github.com/EventEmitter2/EventEmitter2
https://github.com/primus/eventemitter3
简版
https://github.com/mqyqingfeng/EventEmitter
https://github.com/ericz/EventEmitter
其版本存在问题
- 为啥不可重复添加
- off的异常逻辑
- off与nodejs events行为不一致
- 参数可变并不稳妥
once有的两种实现思路
- 属性标记
{
once: true,
listener: ....
}
- 函数包裹,执行一个包裹函数,包裹函数负责清理
EventEmitter.prototype.once = function(type, listener, scope) {
if ('function' !== typeof listener) {
throw new Error('.once only takes instances of Function');
}
var self = this;
function g() {
self.removeListener(type, g);
listener.apply(this, arguments);
};
g.listener = listener;
self.on(type, g);
return this;
};
https://github.com/colxi/getEventListeners 其只是直接修改了原型方法,结果可行,不推荐这么玩。
https://www.zhihu.com/zvideo/1308910938549485568
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry