Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现单例 EventEmitter #42

Open
Inchill opened this issue Sep 25, 2022 · 0 comments
Open

实现单例 EventEmitter #42

Inchill opened this issue Sep 25, 2022 · 0 comments

Comments

@Inchill
Copy link
Owner

Inchill commented Sep 25, 2022

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant