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
92 lines (91 loc) • 2.71 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ddpReactiveDocument = void 0;
const ddpOnChange_js_1 = require("./ddpOnChange.js");
/**
* A reactive document class.
* reactive object won't change when corresponding object is being deleted.
*/
class ddpReactiveDocument {
_ddpReactiveCollectionInstance;
_started;
_data;
_tickers;
_preserve;
constructor(ddpReactiveCollectionInstance, settings) {
this._ddpReactiveCollectionInstance = ddpReactiveCollectionInstance;
this._started = false;
this._data = {};
this._tickers = [];
this._preserve = false;
if (typeof settings === 'object' && settings !== null)
this.settings(settings);
this.start();
}
/**
* Updates reactive object from local collection copies.
*/
_update(newState) {
if (newState) {
// clean object
Object.keys(this._data).forEach((key) => {
// @ts-ignore
delete this._data[key];
});
// assign new state
Object.assign(this._data, newState);
}
else {
// no object clean if not preserved
if (!this._preserve) {
Object.keys(this._data).forEach((key) => {
// @ts-ignore
delete this._data[key];
});
}
}
this._tickers.forEach((ticker) => {
ticker(this.data());
});
}
/**
* Starts reactiveness for the document. This method is being called on instance creation.
*/
start() {
if (!this._started) {
this._update(this._ddpReactiveCollectionInstance.data()[0]);
this._ddpReactiveCollectionInstance._activateReactiveObject(this);
this._started = true;
}
}
/**
* Stops reactiveness for the document.
*/
stop() {
if (this._started) {
this._ddpReactiveCollectionInstance._deactivateReactiveObject(this);
this._started = false;
}
}
/**
* Returns reactive document.
*/
data() {
return this._data;
}
/**
* Runs a function every time a change occurs.
*/
onChange(f) {
const self = this;
return (0, ddpOnChange_js_1.ddpOnChange)(f, self, '_tickers');
}
/**
* Change reactivity settings.
* @param {boolean} settings.preserve - When preserve is true,reactive object won't change when corresponding object is being deleted.
*/
settings({ preserve }) {
this._preserve = !!preserve;
}
}
exports.ddpReactiveDocument = ddpReactiveDocument;