Publish subscribe mode
class EventEmitter {
constructor() {
this.cache = {}
}
//Registration events
$on(eventType, fn) {
//Add event
this.cache[eventType] = this.cache[eventType] || [];
this.cache[eventType].push(fn);
}
//Logout event
$off(eventType) {
if(this.cache[eventType]) {
delete this.cache[name];
}
}
//Trigger event
$emit(eventType) {
if(this.cache[eventType]) {
this.cache[eventType].forEach(handle=>{
handle();
})
}
}
}
//Testing
let eventEmitter = new EventEmitter();
function f(){
console.log("Jason");
}
eventEmitter.$on('click' f);
eventEmitter.$emit('click'); // Jason
EventEmitter. $off ('click '); // the click event logs off
EventEmitter. $emit ('click '); // click personal leave no longer exists