UNPKG

dreamstate

Version:

Store management library based on react context and observers

60 lines (57 loc) 2.15 kB
import { DreamstateError } from '../error/DreamstateError.js'; import { EDreamstateErrorCode } from '../../types/error.js'; import { isCorrectSignalType } from '../../utils/typechecking.js'; /** * Cancels the signal event, preventing further propagation to subsequent listeners. * * This method is used within signal events to stop their execution, ensuring that * no additional subscribers receive the event after cancellation. * * @template D - The type of the signal event data, defaults to `undefined`. * @returns {ISignalEvent<D>} The canceled signal event instance. */ function cancelSignal() { this.canceled = true; return this; } /** * Emits a signal and notifies all subscribed listeners. * * This function constructs a signal event from the provided base data and dispatches it * to all registered listeners within the current scope. If any listener cancels the event, * propagation to subsequent handlers is stopped. * * @template D - The type of the signal event data, defaults to `undefined`. * @param {IBaseSignal<D>} base - The base signal data used to create the event. * @param {TAnyContextManagerConstructor | null} [emitter] - The optional emitter of the signal, * typically a context manager class. * @param {IRegistry} REGISTRY - The registry containing all signal event listeners. * @returns {ISignalEvent<D>} The dispatched signal event instance. */ function emitSignal(base, emitter, REGISTRY) { if (emitter === void 0) { emitter = null; } if (!base || !isCorrectSignalType(base.type)) { throw new DreamstateError(EDreamstateErrorCode.INCORRECT_SIGNAL_TYPE); } var signalEvent = { type: base.type, data: base.data, emitter: emitter, timestamp: Date.now(), cancel: cancelSignal }; // todo: Use for-in and break loop on cancel. REGISTRY.SIGNAL_LISTENERS_REGISTRY.forEach(function (it) { try { if (!signalEvent.canceled) { it(signalEvent); } } catch (error) { console.error("[DS]", "Failed to proceed emitted signal (".concat(String(base.type), "):"), error); } }); return signalEvent; } export { emitSignal };