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.
57 lines • 1.86 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.BroadcastChannel = void 0;
const dirty_checked_unique_collection_js_1 = require("../collection/dirty-checked-unique-collection.js");
/**
* @public
* Strong reference implementation of {@link IBroadcastChannel}.
*/
class BroadcastChannel {
constructor(key) {
this.key = key;
this.listeners = new dirty_checked_unique_collection_js_1.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();
}
}
exports.BroadcastChannel = BroadcastChannel;
//# sourceMappingURL=broadcast-channel.js.map