Skip to content

Instantly share code, notes, and snippets.

@lifeart
Last active May 24, 2021 18:56
Show Gist options
  • Save lifeart/2c4666844a11b1e8536a32d6c776aacc to your computer and use it in GitHub Desktop.
Save lifeart/2c4666844a11b1e8536a32d6c776aacc to your computer and use it in GitHub Desktop.
GlimmerLite web components example
<!doctype html>
<html>
<head>
<title>Glimmer Demo</title>
</head>
<body>
<script src="./app.bundle.js"></script>
<example-app />
</body>
</html>
import { renderComponent } from '@glimmerx/core';
import MyComponent from './src/MyComponent';
import LocaleService from './src/services/LocaleService';
const USE_SHADOW_DOM = false;
function initializeCustomElement(
customElementName: string,
glimmerComponentName: any,
opts: any
): void {
class GlimmerWebElement extends HTMLElement {
connectedCallback() {
let node = USE_SHADOW_DOM ? this.attachShadow({ mode: 'open' }) : this;
renderComponent(glimmerComponentName, { ...opts, ...{ element: node } }).then(() => {
let rootNode = this.lastChild; // may be different (depends on template);
if (rootNode) {
assignAttributes(this, rootNode as any);
}
});
}
}
if (!window.customElements.get(customElementName)) {
window.customElements.define(customElementName, GlimmerWebElement);
}
}
function assignAttributes(fromElement: Element, toElement: Element): void {
let attributes = fromElement.attributes;
for (let i = 0; i < attributes.length; i++) {
let { name, value } = attributes.item(i) as any;
toElement.setAttribute(name, value);
}
}
document.addEventListener(
'DOMContentLoaded',
() => {
initializeCustomElement('example-app', MyComponent, {
services: {
locale: new LocaleService('en_US'),
},
});
},
{ once: true }
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment