Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

聊一聊事件发布订阅机制 #32

Open
bigbigDreamer opened this issue Sep 30, 2019 · 2 comments
Open

聊一聊事件发布订阅机制 #32

bigbigDreamer opened this issue Sep 30, 2019 · 2 comments

Comments

@bigbigDreamer
Copy link
Owner

聊一聊事件发布订阅机制

使用场景

无论是在Vue还是React中,都不可避免的会发生组件之间的数据、状态传递,因此也就出现了事件发布-订阅机制。

先来看一看简单的代码实现吧:

/**
 * @time  2019/9/29 20:52
 * @author  Eric Wang <[email protected]>
 * @desc   事件机制,跟订阅报纸一样,同样的道理,先发布后订阅
 */

const PubSub = (
    _ => {

        // 事件中央调度器
        const handlers = {};

        // 订阅事件
        function subscribe(eventName, fn) {

            // 如果事件未被入队,那么初始化事件对象
            if(!(eventName in handlers)) {
                handlers[eventName] = [];
            }

            // 否则同一事件入队
            handlers[eventName].push(fn);
        }

        // 发布事件
        function publish(eventName, ...data) {
            console.log(handlers[eventName]);

            // 捕获异常
            try{

                // 判断事件
                if(!(eventName in handlers)) {
                    throw new Error("You don't subscribe this Event!")
                }
                handlers[eventName].map(item => {

                    // 参数序列化
                    item(...data);
                });
            } catch (e) {
                console.log(e);
            }
        }

        return {
            subscribe: subscribe,
            publish: publish
        }
    }
)();


PubSub.subscribe("getData",(data1,data2) => {
    console.log(data1,data2);
});

PubSub.publish("getData","数据一","数据二");

释意

下面到了畅所欲言阶段,事件发布订阅依赖事件的中央调度器进行分配调度,而发布与订阅并不会关心过多的事情,实现了一定程度的解耦。

@bigbigDreamer
Copy link
Owner Author

其实,这算是我学习到的第四个设计模式,之前的三个设计模式分别是“工厂函数模式”、“单例模式”、“内省模式”。

@bigbigDreamer
Copy link
Owner Author

其实,我突然想到,还有一种适用场景就是订阅ajax请求过来的数据,请求成功去发布,而在需要使用数据得地方去订阅数据。 @hxrykl

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant