UNPKG

@dubaua/observable

Version:
1 lines 2.84 kB
{"version":3,"file":"observable.min.modern.mjs","sources":["../src/observable.js"],"sourcesContent":["/**\n * @template T\n * @typedef {(next: T, prev: T | undefined) => void} Subscriber\n */\n\n/**\n * Creates reactive object allowing set new value and subscribe to the value change.\n * If new value isn't equal to previous, each callback passed via subscribe method will be fired.\n * @template T\n * @class Observable\n */\n\nclass Observable {\n /** @private @type {T | undefined} */\n internal;\n\n /** @private @type {Array<Subscriber<T>>} */\n callbacks = [];\n\n /** @private @type {T | undefined} */\n initialValue;\n\n /** Allows to set initial value\n * @param {T} [initial]\n * @public\n */\n constructor(initial) {\n this.internal = initial;\n this.initialValue = initial;\n }\n\n /**\n * Higher order function accepting subscriber and returning unsubscribe function\n * @param {Subscriber<T>} callback a function accepting next and prev values\n * @returns {() => void} unsubscribe function stops firing callback\n * @public\n */\n subscribe(callback) {\n if (typeof callback !== 'function') {\n throw new TypeError('[createObservable]: expected callback to be a function.');\n }\n this.callbacks.push(callback);\n return () => {\n const index = this.callbacks.indexOf(callback);\n this.callbacks = this.callbacks.slice(0, index).concat(this.callbacks.slice(index + 1));\n };\n }\n\n /** @returns {T | undefined} @public */\n get value() {\n return this.internal;\n }\n\n /** @param {T | undefined} next @public */\n set value(next) {\n if (next !== this.internal) {\n const prev = this.internal;\n this.internal = next;\n for (let i = 0; i < this.callbacks.length; i++) {\n this.callbacks[i](this.internal, prev);\n }\n }\n }\n\n /**\n * Clears subscribers and restores initial value\n * @public\n */\n reset() {\n this.callbacks = [];\n this.internal = this.initialValue;\n }\n}\n\nexport default Observable;\n"],"names":["Observable","constructor","initial","callbacks","this","internal","initialValue","subscribe","callback","TypeError","push","index","indexOf","slice","concat","value","next","prev","i","length","reset"],"mappings":"AAYA,MAAMA,WAcJC,WAAAA,CAAYC,QATZC,UAAY,GAUVC,KAAKC,SAAWH,EAChBE,KAAKE,aAAeJ,CACtB,CAQAK,SAAAA,CAAUC,GACR,GAAwB,mBAAbA,EACT,UAAUC,UAAU,2DAGtB,OADAL,KAAKD,UAAUO,KAAKF,GACb,KACL,MAAMG,EAAQP,KAAKD,UAAUS,QAAQJ,GACrCJ,KAAKD,UAAYC,KAAKD,UAAUU,MAAM,EAAGF,GAAOG,OAAOV,KAAKD,UAAUU,MAAMF,EAAQ,IAExF,CAGA,SAAII,GACF,YAAYV,QACd,CAGA,SAAIU,CAAMC,GACR,GAAIA,IAASZ,KAAKC,SAAU,CAC1B,MAAMY,EAAOb,KAAKC,SAClBD,KAAKC,SAAWW,EAChB,IAAK,IAAIE,EAAI,EAAGA,EAAId,KAAKD,UAAUgB,OAAQD,IACzCd,KAAKD,UAAUe,GAAGd,KAAKC,SAAUY,EAErC,CACF,CAMAG,KAAAA,GACEhB,KAAKD,UAAY,GACjBC,KAAKC,SAAWD,KAAKE,YACvB"}