fe-notes icon indicating copy to clipboard operation
fe-notes copied to clipboard

实现单例 EventEmitter

Open Inchill opened this issue 3 years ago • 0 comments

class EventEmitter {
  constructor () {
    if (!EventEmitter.instance) {
      this.task = {}
      EventEmitter.instance = this
    }
    return EventEmitter.instance
  }

  on (type, handler) {
    if (!this.task[type]) this.task[type] = []
    this.task[type].push(handler)
  }

  emit (type) {
    if (!this.task[type]) return

    const args = Array.from(arguments).slice(1)
    const handlers = this.task[type]
    for (var i = 0, len = handlers.length; i < len; i++) {
      const handler = handlers[i]
      handler(...args)
    }
  }
}

// var EventEmitter = (function () {
//   var instance
//   return function () {
//     if (!instance) {
//       instance = new BaseEventEmitter()
//       return instance
//     }
//     return instance
//   }
// })()

const eventBus = new EventEmitter()
const eventBus1 = new EventEmitter()

console.log(eventBus === eventBus1) // 打印输出: true

function handleClick(param1, param2) {
  console.log(param1, param2)
}

eventBus.on('click', handleClick)
eventBus.emit('click', 'foo', 'bar') // 打印输出: foo bar

Inchill avatar Sep 25 '22 08:09 Inchill