MJingv / jehol-person-blog

Jehol's Blog 🙋 (hexo+react)
https://mjingv.github.io/JeholBlog/
0 stars 1 forks source link

发布-订阅实现 #58

Open MJingv opened 4 years ago

MJingv commented 4 years ago
class Event {
  constructor () {
    this.handler = {}
  }

  on (name, fn) {
    if (!this.handler[name]) {
      this.handler[name] = []
    }
    this.handler[name].push(fn)
  }

  emit (name, ...args) {
    if (this.handler[name]) {
      this.handler[name].length && this.handler[name].map(i => {
        i(args)
      })
    }
  }
}

let ev = new Event()
ev.on('change', (msg) => {
  console.log('change-----', msg)
})

ev.emit('change', 1, 3, 3)
MJingv commented 4 years ago
class Event {
  constructor () {
    this._events = new Map()
    this._maxListeners = 10
  }

  on (name, fn) {
    let handler = this._events.get(name) || []
    this._events.set(name, [...handler, fn])
    return this
  }

  emit (name, ...args) {
    let handler = this._events.get(name)
    if (!handler || !handler.length) return null
    for (let i in handler) {
      handler[i](args)
    }
    return this
  }

  off (name, fn) {
    let handler = this._events.get(name)
    if (!handler) return
    let res = handler.filter(i => i.toString() !== fn.toString())
    this._events.set(name, res)
    return this
  }

  once (name, fn) {
    let handler = this._events.get(name)
    if (!handler) return
    for (let i in handler) {
      this.off(name, handler[i])
    }
    this.on(name, fn)
    return this
  }
}

let e = new Event()
e.on('change', (name) => {console.log('!!!' + name)}).on('change', (name) => {console.log('~~~' + name)})

e.emit('change', 'jehol')