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

44 阅读1分钟

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

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

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

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

话不多说,上代码实现。

<!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中的实现方式。