当前位置:网站首页>JS simple publish and subscribe class
JS simple publish and subscribe class
2022-07-28 05:56:00 【Quiet sky】
The core idea
- Use a global variable to store the subscription function
- emit When triggered, traverse each variable of the corresponding array and execute
- off Delete the corresponding function from the array
// Some boundary treatments omitted here , Just to express the core implementation method in a minimalist way
class Observe {
cb = {
}
on(eventName, fn) {
this.cb[eventName] = this.cb[eventName] || []
this.cb[eventName].push(fn)
}
emit(eventName, data) {
let arr = this.cb[eventName]
if (arr) {
arr.forEach((fn) => {
fn(data)
})
}
}
off(eventName, fn) {
let arr = this.cb[eventName]
if (arr) {
let newArr = fn ? arr.filter((e) => {
return e !== fn
}) : []
this.cb[eventName] = newArr
}
}
}
边栏推荐
猜你喜欢
随机推荐
蓝桥杯 方格填数
Distance toolbar in ArcMap (distance)
Books - smart investors
常见WAF拦截页面总结
设置滚动条
结果填空 生日蜡烛
书籍-聪明的投资者
正则表达式
(php毕业设计)基于php在线旅游网站管理系统获取
cmd和npm基础命令
null和undefined的区别
命令注入绕过方式总结
单行函数,聚合函数课后练习
数字藏品成文旅产业新热点
DOM模型的相关概念和操作
ArrayList multithreading security solution
Making E-R diagram based on XMIND
Time setting in curd component
扩展欧几里得定理
单调队列,洛谷P1886 滑动窗口









