Skip to content

Latest commit

 

History

History
38 lines (35 loc) · 954 Bytes

手写发布与订阅.md

File metadata and controls

38 lines (35 loc) · 954 Bytes

说明

该笔记文件是最近整理dom相关知识时,将先前记录的笔记进行整理打包,复制于此。

const eventHub = {
    map: {
        // click: [f1 , f2]
    },
    // 订阅
    on: (name, fn) => {
        eventHub.map[name] = eventHub.map[name] || []
        eventHub.map[name].push(fn) // 将 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 } // 从未订阅过 fn
        q.splice(index, 1) // 将 fn 从队列中删除
    }
}

// 测试
eventHub.on('click', console.log)
eventHub.on('click', console.error)
setTimeout(() => {
    eventHub.emit('click', 'blanche')
}, 3000)