@onesy/subscription
Version:
Subscription method management
84 lines (83 loc) • 3.42 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const is_1 = __importDefault(require("@onesy/utils/is"));
const copy_1 = __importDefault(require("@onesy/utils/copy"));
const try_1 = __importDefault(require("@onesy/utils/try"));
const optionsDefault = {
emit: {
priorValue: true,
copy: false,
pre: {},
post: {},
},
};
class OnesySubscription {
constructor(value, options = {}) {
this.value = value;
this.options = options;
this.methods = [];
// alias
this.push = this.emit;
this.options = Object.assign(Object.assign({}, optionsDefault), this.options);
}
get length() { return this.methods.length; }
emit(value, ...other) {
var _a, _b, _c;
const values = [value, ...other];
// Important for use cases,
// to be available pre emit,
// Save value as last emitted value as a previous state optionally
if ((_a = this.options.emit) === null || _a === void 0 ? void 0 : _a.priorValue)
this.value = values.length === 1 ? values[0] : values;
// Pre
// Value might be of simple type so we have to assign a new value to the value
if ((0, is_1.default)('function', (_b = this.options.emit.pre) === null || _b === void 0 ? void 0 : _b.method))
this.options.emit.pre.method(...values);
// Whether to send a copied value version or not,
// it might be useful since if value is of reference type,
// methods in the beginning might update the value,
// and other following methods wouldn't get the
// same value as it was sent to the first method.
const methodValue = this.options.emit.copy ? (0, copy_1.default)(values) : values;
const methods = this.methods.filter(method => (0, is_1.default)('function', method));
// Emit to methods
for (const method of methods)
(0, try_1.default)(() => method(...methodValue));
// Post
// Value might be of simple type so we have to assign a new value to the value
if ((0, is_1.default)('function', (_c = this.options.emit.post) === null || _c === void 0 ? void 0 : _c.method))
this.options.emit.post.method(...values);
}
forEach(...args) {
this.methods.forEach(method => (0, try_1.default)(() => method(...args)));
}
map(value_) {
if (!this.methods.length)
return;
let value = value_;
for (const method of this.methods)
value = (0, try_1.default)(() => method(value));
return value;
}
subscribe(method) {
if ((0, is_1.default)('function', method) && this.methods.indexOf(method) === -1)
this.methods.push(method);
const instance = this;
return {
unsubscribe: () => {
instance.unsubscribe(method);
}
};
}
unsubscribe(method) {
if ((0, is_1.default)('function', method) && this.methods.indexOf(method) > -1) {
const index = this.methods.findIndex(method_ => method_ === method);
if (index > -1)
this.methods.splice(index, 1);
}
}
}
exports.default = OnesySubscription;