UNPKG

undux

Version:

Dead simple state management for React

96 lines 3.22 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Emitter = void 0; var rxjs_observable_1 = require("rxjs-observable"); var ALL = '__ALL__'; var CYCLE_ERROR_MESSAGE = '[undux] Error: Cyclical dependency detected. ' + 'This may cause a stack overflow unless you fix it. \n' + 'The culprit is the following sequence of .set calls, ' + 'called from one or more of your Undux Effects: '; var Emitter = /** @class */ (function () { function Emitter(isDevMode) { if (isDevMode === void 0) { isDevMode = false; } this.isDevMode = isDevMode; this.state = { callChain: new Set(), observables: new Map(), observers: new Map(), }; } /** * Emit an event (silently fails if no listeners are hooked up yet) */ Emitter.prototype.emit = function (key, value) { if (this.isDevMode) { if (this.state.callChain.has(key)) { console.error(CYCLE_ERROR_MESSAGE + Array.from(this.state.callChain).concat(key).join(' -> ')); return this; } else { this.state.callChain.add(key); } } if (this.hasChannel(key)) { this.emitOnChannel(key, value); } if (this.hasChannel(ALL)) { this.emitOnChannel(ALL, value); } if (this.isDevMode) this.state.callChain.clear(); return this; }; /** * Subscribe to an event */ Emitter.prototype.on = function (key) { return this.createChannel(key); }; /** * Subscribe to all events */ Emitter.prototype.all = function () { return this.createChannel(ALL); }; /// private Emitter.prototype.createChannel = function (key) { var _this = this; if (!this.state.observers.has(key)) { this.state.observers.set(key, []); } if (!this.state.observables.has(key)) { this.state.observables.set(key, []); } var observable = new rxjs_observable_1.Observable(function (_) { _this.state.observers.get(key).push(_); return function () { return _this.deleteChannel(key, observable); }; }); this.state.observables.get(key).push(observable); return observable; }; Emitter.prototype.deleteChannel = function (key, observable) { if (!this.state.observables.has(key)) { return; } var array = this.state.observables.get(key); var index = array.indexOf(observable); if (index < 0) { return; } array.splice(index, 1); if (!array.length) { this.state.observables.delete(key); this.state.observers.delete(key); } }; Emitter.prototype.emitOnChannel = function (key, value) { this.state.observers.get(key).forEach(function (_) { return _.next(value); }); }; Emitter.prototype.hasChannel = function (key) { return this.state.observables.has(key); }; return Emitter; }()); exports.Emitter = Emitter; //# sourceMappingURL=emitter.js.map