界面
订阅情况:
- 用户A、B订阅c1
- 用户C订阅c2
点击按钮自动发布消息:
- 每秒发送一条消息到channel:c1
- 每2秒发送一条消息到channel:c2
效果图
代码
<button id="start">自动发布消息</button>
<button id="stop">停止发布消息</button>
<script>
const obj = {}
// 订阅消息的函数
function on(channel, func) {
if (!obj[channel]) obj[channel] = []
obj[channel].push(func)
}
// 发布消息函数
function emit(channel, msg) {
if (!obj[channel]) return;
obj[channel].forEach(f => f(msg))
}
// 订阅channel1消息
on('c1', (msg) => {
console.log('用户A-c1接收消息:', msg)
})
on('c1', (msg) => {
console.log('用户B-c1接收消息:', msg)
})
// 订阅channel2消息
on('c2', (msg) => {
console.log('用户C-c2接收消息:', msg)
})
let channels = []
document.getElementById('start').onclick = () => {
console.log('开始发送消息...')
let a = setInterval(() => {
emit('c1', '每1秒发送消息到c1')
}, 1000);
let b = setInterval(() => {
emit('c2', '每2秒发送消息到c2')
}, 2000);
channels.push(a)
channels.push(b)
}
document.getElementById('stop').onclick = () => {
while (channels.length > 0) {
let obj = channels.splice(0, 1)
clearInterval(obj)
console.log('结束发送消息...')
}
}
</script>