美文网首页
发布订阅模式极简版

发布订阅模式极简版

作者: Chris__Liu | 来源:发表于2020-04-03 15:57 被阅读0次

off与once方法只支持具名函数

  class EventEmitter {
            constructor() {
                this.hub = {}
            }
            $on(eventName, fn) {
                this.hub[eventName] ? this.hub[eventName].push(fn) : this.hub[eventName] = [fn]
            }
            $emit(eventName) {
                this.hub[eventName] && this.hub[eventName].forEach(fn => fn())
            }
            $off(eventName,fn) {
                if(this.hub[eventName]){
                    this.hub[eventName].forEach((item,i)=>{
                        if(item === fn){
                            this.hub[eventName].splice(i,1)
                        }
                    })
                }
            }
            $once(eventName,fn){
                if(this.hub[eventName]){
                    this.hub[eventName].forEach((item,i)=>{
                        if(item === fn){
                            fn()
                            this.$off(eventName,item)
                        }
                    })
                }
            }
        }

相关文章

网友评论

      本文标题:发布订阅模式极简版

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