实现观察者模式

class EventEmitter {
    constructor(){
        this.messageBox = {}
    }

    on(eventName,fn){
        const callbacks = this.messageBox[eventName] || []
        callbacks.push(fn)
        this.messageBox[eventName] = callbacks
    }

    emit(eventName,...args){
        if (this.messageBox[eventName]) {
            const callbacks = this.messageBox[eventName]
            callbacks.forEach((callback)=>{
                callback(...args)
            })
        } else{
            console.log(`${eventName} is not defined`)
        }
    }

    off(eventName,fn){
        if (this.messageBox[eventName]) {
            const index = callbacks.indexOf(fn)
            if (index !== -1) callbacks.slice(index,1)
            else console.log(`${fn} is not defined`)
        } else {
            console.log(`${eventName} is not defined`)
        }
    }

    once(eventName,fn){
        var onlyOnce = function() {
            fn()
            this.off(eventName,onlyOnce)
        }
        this.on(eventName,onlyOnce);
    }
}

 

posted @ 2020-04-14 12:23  想学JS的前端  阅读(175)  评论(0编辑  收藏  举报