- JS实现发布订阅功能
// 发布订阅
const eventHub = {
// 队列MAP, 存放事件名和触发事件
queueMap: {},
// 注册事件
on: (name, fn) => {
eventHub.queueMap[name] = eventHub.queueMap[name] || []
eventHub.queueMap[name].push(fn)
},
// 触发事件
emit: (name, data) => {
const q = eventHub.queueMap[name]
if (!q) return
q.map(fn => fn.call(null, data))
},
// 取消事件
off: (name, fn) => {
const q = eventHub.queueMap[name]
if (!q) return
const index = q.indexOf(fn)
if (index === -1) return
q.splice(index, 1)
}
}
eventHub.on('click', console.log)
eventHub.on('click', console.error)
eventHub.emit('click', 'jnp')
eventHub.off('click', console.log)
标签:订阅,const,name,click,发布,eventHub,queueMap,fn
From: https://www.cnblogs.com/codejnp/p/18234975