UNPKG

@twobirds/microcomponents

Version:

Micro Components Organization Class

81 lines 3.29 kB
import { DC, defineCE, getCE, observe, } from '../microcomponents.js'; class Translator extends DC { #translations = {}; Language = 'en'; Translation = {}; constructor(target, translations, translationTargetObject) { super(target); let that = this; that.Language = 'en'; that.Translation = {}; observe(that); that.#translations = translations; that.Language.observe((lang) => { if (that.#translations.hasOwnProperty(lang)) { that.Translation = { lang: that.#translations[lang] }; } }); that.Translation.bind(translationTargetObject); that.target.setAttribute('language', 'en'); that.Language.notify(); delete that._mc; } onAttributeChanged(ev) { if (!ev.data.newValue) return; switch (ev.data.name) { case 'language': this.Language = ev.data.newValue; break; } } } defineCE('my-tag', class MyTag extends DC { #template = '<button>{lang.click} {counter}</button>'; #languages = { en: { click: 'click me', }, de: { click: 'klick mich', }, }; Dom = {}; constructor(target) { super(target); let that = this; target.innerHTML = this.#template; DC.add(target, 'translator', new Translator(target, that.#languages, target)); delete that._mc; } oneInit(ev) { let that = this; that.Dom = { counter: 0 }; observe(that); that.Dom.bind(that.target); } onClick(ev) { const that = this, c = that.Dom.counter++; ev.data.stopPropagation(); that.target.classList.remove('clicked'); that.target.classList.add(that.Dom.counter > 9 ? 'overClicked' : 'clicked'); } }, ['language']); let MyTag = getCE('my-tag'), fragment = new DocumentFragment(); let start = new Date().getTime(), max = 1000; for (let x = 0; x < max; x++) { fragment.append(new MyTag()); } let end = new Date().getTime(); document.body.appendChild(fragment); setTimeout(() => { console.log('%c \n\nStress Test:\n\n %cInstancing %s web components (%s classes): %c %s ms.', 'font-weight: bold; color: black;', 'font-weight: normal;', max, max * 3, 'font-weight: bold; color: blue;', end - start); let element = document.querySelector('my-tag'); console.log("\n\n%cInspect this tag:%c \n( ...to see the inner structure in the '._mc' property )\n\n %O %c %s", 'font-weight: bold;', 'font-weight: normal;', element, 'font-weight: bold;', '\n\nLook up code in the debugger: test.js\n'); let form = document.querySelector('test-testform'); let formInstance = form._mc.TestTestform; window.form = formInstance; console.log("\n\n%cAttached a global variable 'form':%c \n\n %O %c %s %c %s %c %s", 'font-weight: bold;', 'font-weight: normal;', formInstance, 'font-weight: bold;', '\n\nYou can use it to change input values, e.g. \n\n', 'font-weight: normal;', ' form.data.textInput="other value"', 'font-weight: bold;', '\n\nChanges will be reflected in the form contents, same as vice versa.\n'); DC.trigger(element, 'doSomething'); }, 1000); //# sourceMappingURL=test.js.map