UNPKG

simple-object-state

Version:

An experiemental object oriented state mangment lib

100 lines 3.63 kB
"use strict"; var __spreadArrays = (this && this.__spreadArrays) || function () { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; }; Object.defineProperty(exports, "__esModule", { value: true }); var SimpleObjectStateStoreWrapper = /** @class */ (function () { /** * Initalize with the Class of the Store, we will setup the * store itself later with .Instance and .create() */ function SimpleObjectStateStoreWrapper(Class) { this.Class = Class; this.Listeners = []; this.isCreatedThroughSub = false; } /** Just remove the instance, keep the class as we might re-instantiate */ SimpleObjectStateStoreWrapper.prototype.destructor = function () { if (this.Instance) { this.Instance.destructor(); this.Instance = undefined; this.Listeners = []; this.isCreatedThroughSub = false; } }; /** * Actually setup the store, at this point we would want * the stores state to be changing on subscribed to */ SimpleObjectStateStoreWrapper.prototype.create = function () { if (!this.Instance) { this.Instance = new this.Class(); } this.isCreatedThroughSub = false; return this.Instance; }; SimpleObjectStateStoreWrapper.prototype.getInstance = function () { return this.Instance; }; SimpleObjectStateStoreWrapper.prototype.callAction = function (action, args) { if (this.Instance) { this.Instance.callAction(action, args); } }; SimpleObjectStateStoreWrapper.prototype.onSetState = function () { var _this = this; if (this.Instance) { this.Listeners.forEach(function (callback) { if (callback) { callback(_this.getState()); } else { // maybe they forgot to unsubscribe _this.unsubscribe(callback); } }); } }; SimpleObjectStateStoreWrapper.prototype.getState = function () { var instance = this.getInstance(); if (instance) { return instance.getState(); } else { console.warn('no instance setup yet!'); } return {}; }; SimpleObjectStateStoreWrapper.prototype.subscribe = function (callback) { this.Listeners.push(callback); var hadInstanceBeforeCreate = Boolean(this.Instance); this.create(); if (!hadInstanceBeforeCreate) { this.isCreatedThroughSub = true; } }; SimpleObjectStateStoreWrapper.prototype.unsubscribe = function (callback) { if (!this.Instance) { return; } var listeners = __spreadArrays(this.Listeners); var nextListeners = []; var listener = listeners.pop(); while (listener && listener !== callback) { nextListeners.push(listener); listener = listeners.pop(); } nextListeners = __spreadArrays(nextListeners, listeners); this.Listeners = nextListeners; if (this.isCreatedThroughSub && !this.Listeners.length) { this.destructor(); } }; return SimpleObjectStateStoreWrapper; }()); exports.SimpleObjectStateStoreWrapper = SimpleObjectStateStoreWrapper; //# sourceMappingURL=SimpleObjectStateStoreWrapper.js.map