美文网首页
响应式框架原理5(发布订阅模式简单应用)

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

作者: nomooo | 来源:发表于2020-03-06 20:00 被阅读0次

    事件发布订阅模式?
    可以认为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()
    

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

    相关文章

      网友评论

          本文标题:响应式框架原理5(发布订阅模式简单应用)

          本文链接:https://www.haomeiwen.com/subject/opbhrhtx.html