Skip to content

Latest commit

 

History

History
52 lines (42 loc) · 1.17 KB

参考引用.md

File metadata and controls

52 lines (42 loc) · 1.17 KB

EventEmitter

主流库
https://github.com/EventEmitter2/EventEmitter2 https://github.com/primus/eventemitter3
简版
https://github.com/mqyqingfeng/EventEmitter
https://github.com/ericz/EventEmitter

其版本存在问题

  1. 为啥不可重复添加
  2. off的异常逻辑
  3. off与nodejs events行为不一致
  4. 参数可变并不稳妥

once有的两种实现思路

  1. 属性标记
{
  once: true,
  listener: ....
}
  1. 函数包裹,执行一个包裹函数,包裹函数负责清理
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;
};

getEventListeners

https://github.com/colxi/getEventListeners 其只是直接修改了原型方法,结果可行,不推荐这么玩。

FinalizationRegistry

https://www.zhihu.com/zvideo/1308910938549485568
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry