Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
silesky committed Nov 10, 2023
1 parent cf27677 commit 2c020f1
Showing 1 changed file with 13 additions and 13 deletions.
26 changes: 13 additions & 13 deletions packages/generic-utils/src/emitter/emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,37 +27,37 @@ export class Emitter<Contract extends EmitterContract = EmitterContract> {
constructor(options?: EmitterOptions) {
this.maxListenersPerEvent = options?.maxListenersPerEvent ?? 10
}
private _callbacks: Partial<Contract> = {}
private _warned = false
private callbacks: Partial<Contract> = {}
private warned = false

private _warnIfPossibleMemoryLeak<EventName extends keyof Contract>(
private warnIfPossibleMemoryLeak<EventName extends keyof Contract>(
event: EventName
) {
if (this._warned) {
if (this.warned) {
return
}
if (
this.maxListenersPerEvent &&
this._callbacks[event]!.length > this.maxListenersPerEvent
this.callbacks[event]!.length > this.maxListenersPerEvent
) {
console.warn(
`Event Emitter: Possible memory leak detected; ${String(
event
)} has exceeded ${this.maxListenersPerEvent} callbacks. `
)
this._warned = true
this.warned = true
}
}

on<EventName extends keyof Contract>(
event: EventName,
callback: (...args: Contract[EventName]) => void
): this {
if (!this._callbacks[event]) {
this._callbacks[event] = [callback] as Contract[EventName]
if (!this.callbacks[event]) {
this.callbacks[event] = [callback] as Contract[EventName]
} else {
this._callbacks[event]!.push(callback)
this._warnIfPossibleMemoryLeak(event)
this.callbacks[event]!.push(callback)
this.warnIfPossibleMemoryLeak(event)
}
return this
}
Expand All @@ -79,17 +79,17 @@ export class Emitter<Contract extends EmitterContract = EmitterContract> {
event: EventName,
callback: (...args: Contract[EventName]) => void
): this {
const fns = this._callbacks[event] ?? []
const fns = this.callbacks[event] ?? []
const without = fns.filter((fn) => fn !== callback) as Contract[EventName]
this._callbacks[event] = without
this.callbacks[event] = without
return this
}

emit<EventName extends keyof Contract>(
event: EventName,
...args: Contract[EventName]
): this {
const callbacks = this._callbacks[event] ?? []
const callbacks = this.callbacks[event] ?? []
callbacks.forEach((callback) => {
callback.apply(this, args)
})
Expand Down

0 comments on commit 2c020f1

Please sign in to comment.