<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// bus
/* {
say: [callback1, callback2],
hello: [callback1]
} */
class EventBus {
constructor() {
// 什么时候走的?new EventBus() 就会走这儿
// this 是谁?实例
this.bus = {}
}
// 原型方法
$on(eventType, callback) {
if(this.bus[eventType]) {
this.bus[eventType].push(callback)
} else {
this.bus[eventType] = [callback]
}
}
$emit(eventType, ...args) {
this.bus[eventType].forEach(callback => callback(...args))
}
}
const bus = new EventBus()
// 订阅
bus.$on('say', (num1, num2) => {
console.log(num1 + num2 + '~')
});
bus.$on('say', (num1, num2) => {
console.log(num1 + num2 + '~~')
});
bus.$on('hello', (msg) => {
console.log(msg)
});
// 发布
// 把 this.bus 对应的 say 对应的值,就是数组,把数组中的函数都调用一下
bus.$emit('say', 1, 2);
bus.$emit('hello', 'Hello');
</script>
</body>
</html>
封装EventBus
于 2023-07-29 08:37:59 首次发布