美文网首页
简单的EventEmit(发布订阅者模式)

简单的EventEmit(发布订阅者模式)

作者: 叶小七的真命天子 | 来源:发表于2019-07-30 15:42 被阅读0次
    /**
     * simple eventEmit
     * @type {Object}
     */
    export default class EventEmit {
      constructor () {
        this.handlers = {}
      }
      on (key, fn) {
        if (!this.handlers[key]) {
          this.handlers[key] = []
        }
        this.handlers[key].push(fn)
      }
      emit (...args) {
        if (!args || !args.length) return
        let key = args.shift()
        let fns = this.handlers[key]
        fns.forEach(fn => fn.apply(this, args))
      }
      off (key, fn) {
        let handlers = this.handlers[key]
        if (!handlers) return
        if (!fn) {
          handlers && (handlers.length=0)
        } else {
          const index = handlers.findIndex(item => item === fn)
          index && handlers.splice(index, 1)
        }
      }
    }
    
    

    相关文章

      网友评论

          本文标题:简单的EventEmit(发布订阅者模式)

          本文链接:https://www.haomeiwen.com/subject/vbenrctx.html