<!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>
<input type="button" value="测试01" onclick="fn01()">
<input type="button" value="测试02" onclick="fn02()">
<input type="button" value="测试03" onclick="fn03()">
</body>
</html>
<script>
class EventEmitter{
constructor(){
this.events={};
}
on(name,cb){
this.events[name]=cb;
}
emit(name,data){
this.events[name](data);
}
off(name){
delete this.events[name];
}
}
let event=new EventEmitter();
event.on("张三丰",function(x){
console.log("张三丰",x);
})
event.on("张无忌",function(x){
console.log("张无忌",x);
})
function fn01(){
event.emit("张三丰","疯了");
}
function fn02(){
event.emit("张无忌","变成坤");
}
function fn03(){
event.off("张三丰");
}
</script>