class myEventEmit {
constructor() {
this.events = {};
}
on(type, handler) {
if (!(handler instanceof Function)) {
throw new Error('handler 必须是一个函数');
}
if (type in this.events) {
this.events[type].push(handler);
} else {
this.events[type] = [handler];
}
}
emit(type, params) {
if (type in this.events) {
this.events[type].forEach(handler => {
handler(params);
});
}
}
off(type, handler) {
if (type in this.events) {
this.events[type].splice(this.events[type].indexOf(handler), 1);
}
}
}
let ef = new myEventEmit();
const type = 'type1';
const a1 = params => console.log(1, params);
const a2 = params => console.log(2, params);
const a3 = params => console.log(3, params);
ef.on(type, a1);
ef.on(type, a2);
ef.on(type, a3);
ef.emit(type, 'old');
setTimeout(() => {
ef.off(type, a1);
ef.off(type, a3);
ef.emit(type, 'new');
}, 2000);