实现观察者模式

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

猜你喜欢

转载自www.cnblogs.com/AwenJS/p/12697158.html