qiuhongbingo / blog

Writing something in Issues.
https://github.com/qiuhongbingo/blog/issues
3 stars 0 forks source link

发布订阅模式简单应用 #18

Open qiuhongbingo opened 4 years ago

qiuhongbingo commented 4 years ago
class Notify {
  constructor() {
    this.subscribers = []
  }
  add(handler) {
    this.subscribers.push(handler)
  }
  emit() {
    this.subscribers.forEach(subscriber => subscriber())
  }
}

let notify = new Notify()

notify.add(() => console.log('emit 1'))
notify.add(() => console.log('emit 2'))
notify.emit() // emit 1、emit 2