<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>发布订阅模式</title>
</head>
<body>
<script>
/*
react发布订阅模式-模仿饿了么点单
https://github.com/shuiruohanyu/taro-meituan/tree/master
简单实现发布订阅模式。就是发布消息通知订阅了这一类型的客户
*/
class Event {
constructor(){
this.events = {}; // 定义一个事件容器
}
//监听
on(eventName,callBack){
if(this.events[eventName]){
//存在事件
this.events[eventName].push(callBack)
}else{
//不存在事件
this.events[eventName]=[callBack];
}
}
//触发
emit(eventName,params){
if(this.events[eventName]){
this.events[eventName].map((callBack)=>{
callBack(params);
})
}
}
removeType (eventName) { // 移除订阅类型
delete this.events[eventName]
}
}
const myEvent = new Event();//实例化一个事件管理器
myEvent.on("changeCata",(val)=>{
//监听到改变 进行更新新
console.log(val) //传递的值
})
myEvent.emit("changeCata", '传递的值')
</script>
</body>
</html>