观察订阅模式的简单实现
<!--
* @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>