Last active
October 18, 2022 15:55
-
-
Save shannonmoeller/566d75a004007ece5069dcfe856a02d6 to your computer and use it in GitHub Desktop.
Custom elements without the class.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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