TS编写发布订阅模式
2024-09-08 18:38:25
interface PubSubType {
events: { [key: string]: { name: string, once: boolean, cb: Function }[] }
on(name: string, cb: Function): void
once(name: string, cb: Function): void
emit(name: string, ...arg: Array<any>): void
off(name: string, cb: Function): void
}
class PubSub implements PubSubType {
events: { [key: string]: { name: string, once: boolean, cb: Function }[] }
constructor() {
this.events = {}
}
private eventsOnApi(this: PubSubType, name: string, cb: Function, once: boolean = false) {
const list = this.events[name] || [];
list.push({ name, cb, once })
this.events[name] = list
}
on(name: string, cb: Function): void {
this.eventsOnApi(name, cb)
}
once(name: string, cb: Function): void {
this.eventsOnApi(name, cb, true)
}
emit(name: string, ...arg: Array<any>): void {
const list = this.events[name];
list && list.forEach(item => {
if (item.once) {
item.cb.apply(this, arg)
this.off(name, item.cb)
} else {
item.cb.apply(this, arg)
}
})
}
off(name: string, cb: Function): void {
const list = this.events[name];
if (!list) return
const fileList = list.filter(item => item.cb !== cb)
this.events[name] = fileList
}
}
最新文章
- node crypto md5加密,并解决中文不相同的问题
- 在python中处理XML
- “SSLError: The read operation timed out” when using pip
- FileInputStream类
- mysql更新一个表里的字段等于另一个表某字段的值
- NOIP总结
- 【React Native 实战】旋转图片验证码
- About the Storage allocation
- AnonymousType匿名类型和对象之间的转换
- .Net 多线程开发优化实践
- Zabbix实战-简易教程系列
- wamp apache无法启动的解决方法
- View事件分发
- Codeforces.1045A.Last chance(最大流ISAP 线段树优化建图)
- 查看占用IO的进程
- how-to-view-source-of-chrome-extension
- Azure Storage架构介绍
- webapi Route 特性
- 清理tomcat日志大的文件
- kong 插件开发分析