<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
<h1>test</h1>
<script>
class Observer{
constructor() {
this.massage = {};
}
_on(type, fn) {
if(!this.massage[type]) {
this.massage[type] = [];
}else {
this.massage[type].push(fn);
}
}
_off(type, fn) {
if(!this.massage[type]) {
return;
}
if(!fn) {
this.massage[type] = undefined;
}else {
this.massage[type] = this.massage[type].filter((item)=>{
return item !== fn;
})
}
}
_emit(type) {
if(!this.massage[type]) {
return;
}
this.massage[type].forEach((item)=> {
item();
})
}
}
function handlead() {
let name = 'a订阅';
console.log('a订阅');
}
function handleb() {
let name = 'b订阅';
console.log('b订阅');
}
function handlec() {
console.log('c订阅');
}
let person = new Observer();
person._on('adda', handleb);
person._on('adda', handlead);
person._on('adda', handleb);
person._on('adda', handleb);
person._on('adda', handlec);
person._on('addb', handleb);
person._emit('adda');
console.log(person);
</script>
</body>
</html>