我是靠谱客的博主 酷酷乌龟,这篇文章主要介绍 自己简单写的 事件订阅机制,现在分享给大家,希望可以做个参考。

我写的 简易的事件订触发。

    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)
            })
        }
    }

最后

以上就是酷酷乌龟最近收集整理的关于 自己简单写的 事件订阅机制的全部内容,更多相关内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(119)

评论列表共有 0 条评论

立即
投稿
返回
顶部