export class EventEmitter {
constructor() {
this._events = {}
}
on(evt, fn) {
if (typeof fn !== "function") {
throw new TypeError("The evet-triggered callback must be a function");
}
if (!this._events[evt]) {
this._events[evt] = [fn];
} else {
this._events[evt].push(fn);
}
}
emit(evt, ...args) {
this._events[evt].forEach((fn) => {
fn.apply(this, args);
});
}
off(evt, fn) {
if (!this._events[evt]) return;
if (!fn) { delete this._events[evt] }
const cbLen = this._events[evt].length;
for (let i = 0; i < cbLen; i++) {
if (this._events[evt][i] === fn) {
this._events[evt].splice(i, 1);
break;
}
}
}
}
js手写一个简单的发布订阅EventMitter
于 2024-06-22 18:14:01 首次发布