首页 > 其他分享 >ts实现发布订阅

ts实现发布订阅

时间:2022-10-28 00:55:30浏览次数:45  
标签:订阅 obj log ts eventName 发布 aaa fn caches


interface CacheProps {
    [key: string]: Array<((data:unknown) => void)>;
}

class Observer {
    private caches:CacheProps = {};
    on(eventName: string,fn:((data?:unknown) => void)) {
        this.caches[eventName] = this.caches[eventName]?this.caches[eventName]:[];
        this.caches[eventName].push(fn);
    }
    emit(eventName: string,data?:unknown) {
        if(this.caches[eventName]) {
            this.caches[eventName].forEach((fn)=> {
                fn(data);
            })
        } else {
            return {
                flag: false,
                errMsg: "不存在该函数"
            }
        }
    }
    off(eventName:string,fn:((data?:unknown) => void)) {
        if(this.caches[eventName]) {
            const newCaches = fn?this.caches[eventName].filter(e => e !== fn):[];
            this.caches[eventName] = newCaches;
        }
    }
}
function a() {
    console.log(4);
}
const obj:Observer = new Observer();
obj.on("aaa",()=>{console.log(3)});
obj.on("aaa",()=>{console.log(3)});
obj.on("aaa",a);
console.log(obj)
obj.off("aaa",a);
obj.emit("aaa");

标签:订阅,obj,log,ts,eventName,发布,aaa,fn,caches
From: https://www.cnblogs.com/guozhiqiang/p/16834483.html

相关文章

  • CF1491F Magnets
    首先\(n_1n_2+s_1s_2-n_1s_2-n_2s_1=(n_1-s_1)(n_2-s_2)\)这样可以发现,如果知道任意一块有磁性的磁铁,可以将它和其他磁铁询问得到另一块磁铁的状态(如果为\(\pm1\)......
  • requests模块及openpyxl模块简介
    昨日内容回顾正则表达式字符组字符组内部字符为并列关系。连续字符用'-'连接。特殊符号开头、结尾、数字、任意字符、字母数字下划线。量词多次、一次、指......
  • requests进阶
    一、图片下载下载图片,需获取到图片的url地址和图片名称,通过向图片url发起请求,之后获取.content注意:.text返回的是Unicode型的数据。.content返回的是bytes型也就是......
  • Python-requests 模块
    requests模块Python中原生的基于网络请求的模块,主要用来发送HTTP请求,简单便捷,效率极高.工作流程:指定url发起请求获取响应数据持久化存储requests请求......
  • Echarts基础
    Echarts步骤初始化varechart=echarts.init(dom节点,主题)定义选项optionvaroption={title标题legend图例color调试版本tooltip提示xAx......
  • Python RabbitMQ pika的安装及fanout消息订阅模式的使用
    RabbitMQ是实现了高级消息队列协议(AMQP)的开源消息代理软件,RabbitMQ服务器是用Erlang语言编写的,而集群和故障转移是构建在开放电信平台框架上的。所有主要的编程语言均有......
  • 网狐荣耀6701、6801版本游戏的环境搭建与编译、发布
    代码已提交:https://pan.baidu.com/s/1kKR-vieIzkagcjmYcG75KQ提取码:4dxt 之前在网上买了一套源码,完完整整从头到尾研究了一遍,踩过很多坑。在这里简单记录下。参考了一......
  • D. Problem with Random Tests
    传送门题意:给出一个字符串,然后,从这个字符串中取两个子串s1,s2,要求两个字符串的或最大思路:首先,先去s1从第一个非0开始取整段,记录第一个非0的位置为p1,因为或位数......
  • 选择Visual Components软件的五大理由
    1、更好的性能开发视觉组件是为了充分利用64位Windows环境。这意味着更好的图形、更快的加载时间和更流畅的用户体验。导航大布局是流动的。内存管理不断优化,以提高仿......
  • echarts相关配置(随时添加)
    option--tooltip图层的信息提示框backgroundColor、textStyle:{color、font-size}option-legend图例属性设置(top、right、x、y等)、orient:(vertical、horizontal)option-seri......