手把手带你实现发布订阅模式

发布订阅是设计模式的一种。简单理解,你微信订阅了某些公众号,这些公众号发布新文章时,微信就会通知你,这就是发布订阅的一种。

vue的响应式设计就是结合了数据劫持和发布订阅模式实现的,要想理解vue的设计,就必须要搞懂发布订阅模式。

核心:订阅者,发布者,调度中心。

  • 订阅者:把自己想订阅的事件注册到调度中心。
  • 调度中心:发布者发布任务时,通知订阅者(调用订阅者注册的代码)
  • 发布者:发布任务到调度中心。

话不多说,上代码实现。

xml 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        class Publish {
            constructor() {
                // 调度中心,订阅者把自己要订阅的东西注册到这里
                // this.events = {
                //      event1: [fn1, fn2, fn3]
                //      event2: [fn1, fn2]
                //}
                this.events = {}
            }

            // 订阅,订阅者把把事件注册到调度中心
            $on(type, fn) {
                if (!this.events[type]) {
                    this.events[type] = []
                }

                this.events[type].push(fn)
            }

            // 发布,通过调度中心发布
            $emit(type) {
                if (this.events[type]) {
                    const args = Array.prototype.slice.call(arguments, 1)
                    this.events[type].forEach(fn => {
                        fn(...args)
                    });
                }
            }
        }

        const eventHub = new Publish()

        // 订阅:把事件注册到调度中心
        eventHub.$on('sum', function() {
            const total = [...arguments].reduce((x, y) => x + y)
            console.log(total)
        })

        // 发布:如果有人订阅,那么就执行注册的代码
        eventHub.$emit('sum', 1, 2, 3)
    </script>
</body>
</html>

发布订阅有很多种实现方式,这只是在Vue中的实现方式。

相关推荐
荒诞英雄1 小时前
从 17MB Vendor 大包到按需加载:Vite 多入口 Vue 组件库首屏优化实践
vue.js·vite
一只猫的梦1 小时前
自动化模块 (Automation Module)
前端·chrome
熊猫钓鱼>_>1 小时前
Electron:当 Web 技术统治桌面
大数据·前端·javascript·人工智能·架构·electron·agent
德福危险1 小时前
从盲打xss到到模板注入:unix靶机渗透之Tempus_fugit4
前端·unix·xss
JavaGuide1 小时前
又一个画图 Skill 开源,再见手动画 draw.io!
前端·后端·github
workflower2 小时前
室内外配送机器人-应用路径
人工智能·机器学习·设计模式·矩阵·自动化
一只猫的梦2 小时前
AI 适配器架构
前端·chrome
谭光志2 小时前
AI 是怎么操作浏览器的——browser use 实现原理
前端·javascript·ai编程
weixin_471383032 小时前
args,...args与Parameters<T>
开发语言·前端