@geogirafe/lib-geoportal
Version:
GeoGirafe is a flexible application to build online geoportals.
49 lines (48 loc) • 2.11 kB
JavaScript
import GirafeSingleton from '../../base/GirafeSingleton.js';
export default class ComponentManager extends GirafeSingleton {
components = {};
componentsCallbacks = [];
registerComponent(component) {
this.components[component.name] ??= [];
this.components[component.name].push(component);
for (const componentCallbacks of this.componentsCallbacks) {
if ((componentCallbacks.componentType && component instanceof componentCallbacks.componentType) ||
(componentCallbacks.componentName && componentCallbacks.componentName === component.name)) {
componentCallbacks.callbacks.forEach((callback) => callback(component));
}
}
}
registerComponentCallback(componentOrName, callback) {
const componentType = typeof componentOrName !== 'string' ? componentOrName : undefined;
const componentName = typeof componentOrName === 'string' ? componentOrName : undefined;
let entry = this.componentsCallbacks.find((c) => c.componentType === componentType && c.componentName === componentName);
if (entry) {
entry.callbacks.push(callback);
}
else {
entry = { componentType, componentName, callbacks: [callback] };
this.componentsCallbacks.push(entry);
}
// If some components were already registered, the callback is called directly on them.
for (const registeredComponent of this.getRegisteredComponentsForEntry(componentType, componentName)) {
callback(registeredComponent);
}
}
getRegisteredComponentsForEntry(componentType, componentName) {
if (componentName) {
return this.components[componentName] ?? [];
}
if (componentType) {
return this.getComponents(componentType);
}
return [];
}
getComponents(type) {
return Object.values(this.components)
.flat()
.filter((c) => c instanceof type);
}
getComponentsByName(name) {
return this.components[name];
}
}