@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
62 lines • 2.37 kB
JavaScript
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
class EventEmitter {
static createInstance(id) {
return new EventEmitter(id);
}
constructor(id) {
_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 = _objectSpread(_objectSpread({}, 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;
scope.__EEE__[id].instances.push(this);
this.id = id;
this.listeners = [];
return this;
}
listen(fn) {
if (!this.listeners.includes(fn)) {
this.listeners.push(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;
export default EventEmitter;
//# sourceMappingURL=EventEmitter.js.map