@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
66 lines • 1.89 kB
JavaScript
import _defineProperty from "@babel/runtime-corejs3/helpers/esm/defineProperty";
import _pushInstanceProperty from "core-js-pure/stable/instance/push.js";
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;
_pushInstanceProperty(_context = scope.__EEE__[id].instances).call(_context, this);
this.id = id;
this.listeners = [];
return this;
}
listen(fn) {
if (!this.listeners.includes(fn)) {
var _context2;
_pushInstanceProperty(_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;
export default EventEmitter;
//# sourceMappingURL=EventEmitter.js.map