rc-js-util
Version:
A collection of TS and C++ utilities to help writing performant and correct applications, achieved through strict typing and (removable) invariant checking.
53 lines • 1.66 kB
JavaScript
import { DirtyCheckedUniqueCollection } from "../collection/dirty-checked-unique-collection.js";
/**
* @public
* Strong reference implementation of {@link IBroadcastChannel}.
*/
export class BroadcastChannel {
constructor(key) {
this.key = key;
this.listeners = new DirtyCheckedUniqueCollection();
}
addListener(maybeStore, listener) {
if (listener == null) {
// no store was supplied
listener = maybeStore;
}
else {
// we have both args
maybeStore.registerCleanup(() => this.removeListener(listener));
}
this.listeners.add(listener);
}
addOneTimeListener(maybeStore, listener) {
const hasStore = listener != null;
if (listener == null) {
// no store was supplied
listener = maybeStore;
}
const temporaryListener = {
[this.key]: (...args) => {
this.removeListener(temporaryListener);
return listener[this.key](...args);
}
};
this.addListener(temporaryListener);
if (hasStore) {
maybeStore.registerCleanup(() => this.removeListener(temporaryListener));
}
}
removeListener(listener) {
this.listeners.delete(listener);
}
emit(...args) {
const listeners = this.listeners.getArray();
const key = this.key;
for (let i = 0, iEnd = listeners.length; i < iEnd; i++) {
listeners[i][key](...args);
}
}
getTargets() {
return this.listeners.getArray();
}
}
//# sourceMappingURL=broadcast-channel.js.map