UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

75 lines (74 loc) 2.62 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _push = _interopRequireDefault(require("core-js-pure/stable/instance/push.js")); function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } class EventEmitter { static createInstance(id) { return new EventEmitter(id); } constructor(id) { var _context; _defineProperty(this, "update", data => { this.set(data); scope.__EEE__[this.id].instances.forEach(instance => { instance.listeners.forEach(fn => { if (typeof fn === 'function') { fn(instance.get()); } }); }); }); _defineProperty(this, "set", data => { scope.__EEE__[this.id].data = { ...scope.__EEE__[this.id].data, ...data }; }); _defineProperty(this, "get", () => { return scope.__EEE__[this.id].data; }); scope.__EEE__ = scope.__EEE__ || {}; if (!scope.__EEE__[id]) { scope.__EEE__[id] = { instances: [], count: 0, data: {} }; } scope.__EEE__[id].count = scope.__EEE__[id].count + 1; (0, _push.default)(_context = scope.__EEE__[id].instances).call(_context, this); this.id = id; this.listeners = []; return this; } listen(fn) { if (!this.listeners.includes(fn)) { var _context2; (0, _push.default)(_context2 = this.listeners).call(_context2, fn); } return this; } unlisten(fn) { for (let i = 0, l = this.listeners.length; i < l; i++) { if (!fn || fn && fn === this.listeners[i]) { this.listeners[i] = null; } } } remove() { this.unlisten(); scope.__EEE__[this.id].count = scope.__EEE__[this.id].count - 1; if (scope.__EEE__[this.id].count <= 0) { delete scope[this.id]; } } } const scope = typeof window !== 'undefined' ? window : EventEmitter; var _default = exports.default = EventEmitter; //# sourceMappingURL=EventEmitter.js.map