观察订阅模式

观察订阅模式的简单实现

<!--
 * @Author: fangshiming
 * @Date: 2021-05-20 20:47:39
 * @LastEditTime: 2021-05-24 21:57:52
 * @Description: 观察订阅模式
-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        class Pubsub {
            constructor(){
                /**
                 * @description: 事件注册中心
                 */
                this.handler = {};
            }

            /**
             * @description: 事件订阅
             * @param { String } eventName 事件名
             * @param { Function } callback 回调函数
             * @return {*} 无返回值
             */
            on(eventName, callback){
                if(!this.handler[eventName]){
                    this.handler[eventName] = [];
                }
                this.handler[eventName].push(callback);
            }

            
            /**
             * @description: 事件触发
             * @param { String } eventName 事件名
             * @param {*} params 事件参数
             * @return { void }
             */
            emit(eventName, ...params){
                const param = [].slice.call(arguments, 1);
                const fns = this.handler[eventName];
                if(fns && fns.length !== 0){
                    this.handler[eventName].forEach((fn) => {
                        fn.apply(this, param);
                    });
                }else{
                    console.info("没有订阅者");
                }
            }

            /**
             * @description: 取消事件订阅
             * @param { String } eventName 事件名
             * @return { void} 
             */
            cancel(eventName){
                if(this.handler[eventName]){
                    this.handler[eventName] = null;
                }else{
                    console.info("事件未注册");
                }
            }
        }

        const pubsub = new Pubsub();
        pubsub.on("hello", (res) => {
            console.log(res); // "world"
        });
        pubsub.emit("hello", "world");
        pubsub.cancel("hello");
    </script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值