建议大家从监听开始看,先看on,再看emit,顺着执行过程看更容易明白哦
<!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>
<button class="emit">发送</button>
<script>
// 类
class CKEventBus {
constructor() {
this.eventBusObj = {}
}
// 监听,参数是需要监听的函数名,回调函数,因为可能不止需要监听一个函数,所以把函数存储到数组中
on(eventBusName, eventBusFn) {
// 先拿到存储的回调函数
let fns = this.eventBusObj[eventBusName]
// 如果没有,就给个默认值
if(!fns) {
fns = []
// 相当于给对象添加属性,并且给属性赋值
this.eventBusObj[eventBusName] = fns
}
// 将回调函数储存
fns.push(eventBusFn)
}
emit(eventBusName, ...args) {
// 先拿到存储的回调函数
const fns = this.eventBusObj[eventBusName]
// 如果没有,直接返回
if(!fns) return
// 便利调用回调函数
fns.forEach(fn => {
fn(...args)
});
}
}
// 实例
const eventBus = new CKEventBus()
eventBus.on('emitClick', (name, age, height) => {
console.log("emitClick00001", name, age, height);
})
eventBus.on('emitClick', (name, age, height) => {
console.log("emitClick00002", name, age, height);
})
eventBus.on('emitClick1', () => {
console.log("emitClick00001");
})
const btn = document.querySelector(".emit")
btn.onclick = () => {
console.log("自己监听到了");
eventBus.emit('emitClick', 'ck', 18, 188)
}
</script>
</body>
</html>