【设计模式】JavaScript 手写发布订阅
核心代码
// 核心:监听、触发、关闭
const PubSub = {
map: {
// click:[fn1, fn2] // 对应事件发布队列
},
// 监听
on: (name, fn) => {
PubSub.map[name] = PubSub.map[name] || []
PubSub.map[name].push(fn) // 存入队列
},
// 触发
emit: (name, data) => {
const q = PubSub.map[name]
if (!q) return
q.forEach((f) => f.call(undefined, data)) // 触发对应事件队列的所有事件
},
// 关闭
off: (name, fn) => {
const q = PubSub.map[name]
if (!q) return
const index = q.indexOf(fn)
console.log(index)
if (index < 0) return
q.splice(index, 1) // 删除
},
}
测试用例
function fn1(text) {
console.log('自定义函数1:', text)
}
function fn2(text) {
console.log('自定义函数2:', text)
}
// 监听事件
PubSub.on('click', fn1)
PubSub.on('click', fn2)
setTimeout(() => {
// 触发
PubSub.emit('click', '我是触发事件的参数1')
// 关闭
PubSub.off('click', fn1) // 关闭 fn1
PubSub.emit('click', '我是触发事件的参数2')
console.log(PubSub.map);
}, 1000)
测试结果
分类:
设计模式
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步