原理

原理就是发布-订阅。
本次实现了几个功能

  • on 注册事件
  • emit 触发事件
  • off 注销事件
  • once 执行一次后注销事件
  • newListener 每次注册新事件时触发

代码如下:

  1. function EventEmitter() {
  2. this._events = {};
  3. }
  4. EventEmitter.prototype.on = function (eventName, callback) {
  5. if (!this._events) {
  6. this._events = Object.create(null);
  7. }
  8. if (eventName !== 'newListener') {
  9. this._events['newListener'] ? this._events['newListener'].forEach(fn => fn.call(this, eventName)) : void 0;
  10. }
  11. if (this._events[eventName]) {
  12. this._events[eventName].push(callback);
  13. } else {
  14. this._events[eventName] = [callback];
  15. }
  16. }
  17. EventEmitter.prototype.emit = function (eventName, ...args) {
  18. if (!this._events) {
  19. this._events = Object.create(null);
  20. }
  21. if (this._events[eventName]) {
  22. this._events[eventName].forEach(fn => fn.call(this, ...args))
  23. }
  24. }
  25. EventEmitter.prototype.off = function (eventName, callback) {
  26. if (!this._events) {
  27. this._events = Object.create(null);
  28. }
  29. if (this._events[eventName]) {
  30. this._events[eventName] = this._events[eventName].filter(fn => {
  31. return fn !== callback && fn.l !== callback
  32. })
  33. }
  34. }
  35. EventEmitter.prototype.once = function (eventName, callback) {
  36. if (!this._events) {
  37. this._events = Object.create(null);
  38. }
  39. function one(...args) {
  40. callback(...args);
  41. this.off(eventName, one)
  42. }
  43. one.l = callback;
  44. this.on(eventName, one);
  45. }
  46. module.exports = EventEmitter;