手写实现 订阅-发布,超简单

  1.  所有的事件存放在一个对象中
  2. 每个事件的回调函数是一个数组,有多个回调
class EventBus {
    allEvent = {}
    constructor() {
        // 
    }
    on(name, callback) {
        if (this.allEvent[name]) {
            this.allEvent[name] = [...this.allEvent[name], callback]
            return
        }
        this.allEvent[name] = [callback]
    }
    off(name, callback) {
        if (!this.allEvent[name]) {
            return new Error('no event')
        }
        // once
        if (!callback) {
            delete this.allEvent[name]
            return
        }
        const target = this.allEvent[name].filter(item => callback !== item)
        if (target.length) {
            this.allEvent[name] = target
        } else {
            return new Error('no callback')
        }
    }
    emit(name) {
        if (!this.allEvent[name]) {
            return new Error('no event')
        }
        const callbackArr = this.allEvent[name]
        const params = [...arguments].slice(1)
        callbackArr.forEach(item => {
            item(...params)
        })
    }
    once(name, ...args) {
        this.emit(name, ...args)
        this.off(name)
    }
}

const eventBus = new EventBus()

function setName(name) {
    console.log('触发 setname', name)
}
function setName1(name) {
    console.log('触发 setname1', name)
}
eventBus.on('set-name', setName)
eventBus.on('set-name', setName1)
// eventBus.once('set-name', 'once')
// eventBus.off('set-name', setName1)
eventBus.emit('set-name', 'cat')
setTimeout(() => {
    eventBus.emit('set-name', 'dog')
}, 1000);

function setAge(age) {
    console.log('设置age', age)
}
// eventBus.on('set-age', setAge)
// eventBus.off('set-age', setAge)
// eventBus.once('set-age', '12')

你可能感兴趣的:(javascript,前端,vue.js)