Skip to content

Commit

Permalink
Merge pull request #463 from THEOplayer/feature/eventlistener_array
Browse files Browse the repository at this point in the history
Properly support passing an array of events for a listener
  • Loading branch information
tvanlaerhoven authored Dec 23, 2024
2 parents d023644 + 2ebb629 commit f49d999
Showing 1 changed file with 26 additions and 8 deletions.
34 changes: 26 additions & 8 deletions src/internal/adapter/event/DefaultEventDispatcher.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,25 @@
import type { EventDispatcher, EventMap, StringKeyOf } from '../../../api/event/EventDispatcher';
import type { EventListener } from '../../../api/event/EventListener';
import type { EventDispatcher, EventMap, StringKeyOf } from 'react-native-theoplayer';
import type { EventListener } from 'react-native-theoplayer';
import { arrayRemoveElement } from '../../utils/arrayUtil';

export class DefaultEventDispatcher<TMap extends EventMap<StringKeyOf<TMap>>> implements EventDispatcher<TMap> {
readonly _eventListeners: Map<StringKeyOf<TMap>, EventListener<TMap[StringKeyOf<TMap>]>[]> = new Map();

addEventListener<K extends StringKeyOf<TMap>>(type: K, listener: EventListener<TMap[K]>): void {
addEventListener<K extends StringKeyOf<TMap>>(type: K | readonly K[], listener: EventListener<TMap[K]>): void {
if (typeof listener !== 'function') {
return;
} else if (Array.isArray(type)) {
type.forEach((t) => this.addSingleEventListener(t, listener));
} else {
this.addSingleEventListener(type as K, listener);
}
}

private addSingleEventListener<K extends StringKeyOf<TMap>>(type: K, listener: EventListener<TMap[K]>): void {
if (!this._eventListeners.has(type)) {
// @ts-ignore
this._eventListeners.set(type, [listener]);
this._eventListeners.set(type, [listener as EventListener<TMap[StringKeyOf<TMap>]>]);
} else {
// @ts-ignore
this._eventListeners.get(type)?.push(listener);
this._eventListeners.get(type)?.push(listener as EventListener<TMap[StringKeyOf<TMap>]>);
}
}

Expand All @@ -26,7 +34,17 @@ export class DefaultEventDispatcher<TMap extends EventMap<StringKeyOf<TMap>>> im
}
};

removeEventListener<K extends StringKeyOf<TMap>>(type: K, listener: EventListener<TMap[K]>): void {
removeEventListener<K extends StringKeyOf<TMap>>(type: K | readonly K[], listener: EventListener<TMap[K]>): void {
if (typeof listener !== 'function') {
return;
} else if (Array.isArray(type)) {
type.forEach((t) => this.removeSingleEventListener(t, listener));
} else {
this.removeSingleEventListener(type as K, listener);
}
}

private removeSingleEventListener<K extends StringKeyOf<TMap>>(type: K, listener: EventListener<TMap[K]>): void {
const listeners = this._eventListeners.get(type);
if (listeners) {
arrayRemoveElement(listeners, listener);
Expand Down

0 comments on commit f49d999

Please sign in to comment.