UNPKG

simpleddp-node

Version:

The aim of this library is to simplify the process of working with meteor server over DDP protocol using external JS environments

69 lines (68 loc) 1.91 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ddpReducer = void 0; const ddpOnChange_js_1 = require("./ddpOnChange.js"); /** * A reducer class for a reactive document. * @constructor */ class ddpReducer { _ddpReactiveCollectionInstance; _reducer; _started = false; _data = { result: null }; _tickers = []; _initialValue; constructor(ddpReactiveCollectionInstance, reducer, initialValue) { this._ddpReactiveCollectionInstance = ddpReactiveCollectionInstance; this._reducer = reducer; this._initialValue = initialValue; this.start(); } /** * Forcibly reduces reactive data. */ doReduce() { if (this._started) { this._data.result = this._ddpReactiveCollectionInstance.data().reduce(this._reducer, this._initialValue); this._tickers.forEach((ticker) => { ticker(this.data().result); }); } } /** * Starts reactiveness for the reduced value of the collection. * This method is being called on instance creation. */ start() { if (!this._started) { this.doReduce(); this._ddpReactiveCollectionInstance._activateReducer(this); this._started = true; } } /** * Stops reactiveness. */ stop() { if (this._started) { this._ddpReactiveCollectionInstance._deactivateReducer(this); this._started = false; } } /** * Returns reactive reduce. */ data() { return this._data; } /** * Runs a function every time a change occurs. * @param {Function} f - Function which recieves a reduced value at each change. */ onChange(f) { const self = this; return (0, ddpOnChange_js_1.ddpOnChange)(f, self, '_tickers'); } } exports.ddpReducer = ddpReducer;