UNPKG

@twobirds/microcomponents

Version:

Micro Components Organization Class

77 lines (62 loc) 1.58 kB
'use strict'; import { DC } from './MC.js'; import { kebabToPascal } from './helpers.js'; class CeBaseClass extends HTMLElement { constructor() { super(); } connectedCallback() { (DC as any).trigger(this, 'Connected'); } disconnectedCallback() { (DC as any).trigger(this, 'Disconnected'); } adoptedCallback() { (DC as any).trigger(this, 'Adopted'); } attributeChangedCallback(name: string, oldValue: any, newValue: any) { (DC as any).trigger(this, 'AttributeChanged', { name, oldValue, newValue }); } } function createNamedClass( name: string, ClassBody: { new (...args: any[]): any } ) { return Object.defineProperty(ClassBody, 'name', { value: name }); } export function defineCE( tagName: string, DefinitionClass: { new (...args: any[]): any }, observedAttributes: string[] = [] ) { if (customElements.get(tagName)) { console.warn(`IGNORED: Custom element "${tagName}" is already defined!`); return; } if (!tagName.includes('-')) { throw new Error( 'createCustomElement: tagName must contain at least one hyphen ("-").' ); } let name = kebabToPascal(tagName); customElements.define( tagName, createNamedClass( name, class extends CeBaseClass { instance: any; constructor(data?: any) { super(); let instance = new DefinitionClass(this, data); DC.add(this, name, instance); } static get observedAttributes() { return observedAttributes; } } ) ); } export function getCE(tagName: string): CustomElementConstructor | undefined { return customElements.get(tagName); }