Components Future Notes

Naming & Routing

We are considering the possibility of a dual-routing architecture.

The component class itself might have a component name built into it using a TypeScript decorator, like so

Concept code

function Component(name: string) {
    return function (constructor: Function) {
        Reflect.defineMetadata('componentName', name, constructor);
    }
}
@Component('my-component')
class MyComponent {
    constructor() {
        console.log('MyComponent initialized');
    }
}

@Component('another-component')
class AnotherComponent {
    constructor() {
        console.log('AnotherComponent initialized');
    }
}
import 'reflect-metadata';

function createComponentFromAttribute(attrValue: string): any {
    const components = [MyComponent, AnotherComponent];

    for (const component of components) {
        const name = Reflect.getMetadata('componentName', component);
        if (name === attrValue) {
            return new component();
        }
    }

    throw new Error(`Component with name "${attrValue}" not found.`);
}

// Usage
const component = createComponentFromAttribute('my-component'); // Instantiates `MyComponent`
function initializeComponents() {
    const elements = document.querySelectorAll('[data-component]');
    elements.forEach(elem => {
        const componentName = elem.getAttribute('data-component');
        if (componentName) {
            const componentInstance = createComponentFromAttribute(componentName);
            if (componentInstance) {
                console.log(`${componentName} component initialized`, componentInstance);
            }
        }
    });
}

Last updated