Skip to content

发布订阅模式

三个 API

on:监听事件

off:取消监听事件

emit:触发事件

javascript
const eventHub = {
    map: {},
    on: (name, fn) => {
        eventHub.map[name] = eventHub.map[name] || []
        eventHub.map[name].push(fn)
    },
    emit: (name, data) => {
        const q = eventHub.map[name]
        if (!q) return
        q.map(f => f.call(null, data))
        return undefined
    },
    off: (name, fn) => {
        const q = eventHub.map[name]
        if (!q) return
        const index = q.indexOf(fn)
        if (index < 0) return
        q.splice(index, 1)
    }
}

eventHub.on('click', console.log)
eventHub.off('click', console.error)

setTimeout(() => {
    eventHub.emit('click', 'johnny')
}, 3000)

参考资料