本身简朴写的 事宜定阅机制

我写的 浅易的事宜订触发。

    export  const Event = function () {
       // 范例
       this.typeList = {}
    }
    Event.prototype.on = function ({type, fn}){
        if (this.typeList.hasOwnProperty(type)) {
            this.typeList[type].push(fn)
        } else {
            this.typeList[type] = []
            this.typeList[type].push(fn)
        }
    }
    Event.prototype.off = function({type, fn})  {
       if (this.typeList.hasOwnProperty(type)) {
             let list = this.typeList[type]
          let index = list.indexOf(fn)
          if (index !== -1 ) {
                 list.splice(index, 1)
          }
          
       } else {
            console.warn('not has this type')
       }
    }
    Event.prototype.once = function ({type, fn}) {
       const fixFn = (value) => {
            fn.call(this, value)
            this.off({type, fn: fixFn})
       }
       this.on({type, fn: fixFn})
    }
    Event.prototype.trigger = function (type, value, context){
        context = context ? context : null    
        if (this.typeList.hasOwnProperty(type)) {
            this.typeList[type].forEach(fn => {
                fn.call(context, value)
            })
        }
    }
    原文作者:L6zt
    原文地址: https://segmentfault.com/a/1190000013484603
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞