Skip to content

Instantly share code, notes, and snippets.

@shannonmoeller
Last active October 18, 2022 15:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shannonmoeller/566d75a004007ece5069dcfe856a02d6 to your computer and use it in GitHub Desktop.
Save shannonmoeller/566d75a004007ece5069dcfe856a02d6 to your computer and use it in GitHub Desktop.
Custom elements without the class.
export function define(name, init) {
class CustomElement extends HTMLElement {
#connection = null;
#initialized = false;
get signal() {
return this.#connection?.signal;
}
connectedCallback() {
if (!this.isConnected) {
return;
}
this.#connection?.abort();
this.#connection = new AbortController();
if (!this.#initialized) {
this.#initialized = true;
init(this);
}
}
disconnectedCallback() {
if (this.isConnected) {
return;
}
this.#connection?.abort();
this.#connection = null;
}
}
customElements.define(name, CustomElement);
return CustomElement;
}
<!doctype html>
<title>Dice Roller</title>
<script type="module">
import { define } from './define.js';
define('dice-roller', (el) => {
let button = el.querySelector('button');
let input = el.querySelector('input');
button.addEventHandler('click', () => {
input.value = Math.floor(Math.random() * 6) + 1;
});
});
</script>
<dice-roller>
<button>Roll</button>
<input readonly />
</dice-roller>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment