19 lines
448 B
JavaScript
19 lines
448 B
JavaScript
|
|
export class EventEmitter {
|
||
|
|
constructor() {
|
||
|
|
this._events = Object.create(null)
|
||
|
|
}
|
||
|
|
on(type, fn) {
|
||
|
|
(this._events[type] || (this._events[type] = [])).push(fn)
|
||
|
|
}
|
||
|
|
emit(type, ...args) {
|
||
|
|
(this._events[type] || []).forEach(fn => fn(...args))
|
||
|
|
}
|
||
|
|
off(type, fn) {
|
||
|
|
if (!fn) this._events[type] = []
|
||
|
|
else {
|
||
|
|
const idx = (this._events[type] || []).indexOf(fn)
|
||
|
|
if (idx > -1) this._events[type].splice(idx, 1)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|