响应式框架原理5(发布订阅模式简单应用)

2020-03-06  本文已影响0人  nomooo

事件发布订阅模式?
可以认为JavaScript本身就是事件驱动型语言,比如,应用中对一个button进行了事件绑定,用户点击会触发按钮上面的click事件,是因为此时有特定程序正在监听这个事件,随之触发了相关的处理程序。

简单实现这样的模式

            class Notify {
                constructor() {
                    this.subscribers = []
                }
                add(handler) {
                    this.subscribers.push(handler)
                }
                emit() {
                    this.subscribers.forEach(subscriber => subscriber())
                }
            }

使用时

            let notify = new Notify()
            
            notify.add(() => {
                console.log('emit here')
            })
            
            notify.emit()

这就是一个简单实现的“事件发布订阅模式”,只是启发思路。

上一篇下一篇

猜你喜欢

热点阅读