Created
March 10, 2020 03:17
-
-
Save kristoferjoseph/bbf07976d8b66f599fa6595997e948cb to your computer and use it in GitHub Desktop.
Stock JavaScript Web Component Counter
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> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Dam Counter</title> | |
</head> | |
<body> | |
<template id="dam-count-template"> | |
<button class="dam-count-btn"></button> | |
</template> | |
<dam-count count=5></dam-count> | |
<script type="module"> | |
class DamCount extends HTMLElement { | |
constructor() { | |
super() | |
this.updateCount = this.updateCount.bind(this) | |
this.btn | |
const template = document.getElementById('dam-count-template') | |
const templateContent = template.content | |
const shadow = this.attachShadow({mode: 'open'}) | |
shadow.appendChild(templateContent.cloneNode(true)) | |
} | |
static get observedAttributes() { | |
return ['count'] | |
} | |
attributeChangedCallback(name, o, n) { | |
if (name === 'count') { | |
if (this.btn) | |
this.btn.textContent = `Count ${n}` | |
} | |
} | |
updateCount(e) { | |
let currentCount = this.getAttribute('count') | |
this.setAttribute('count', Number(currentCount) + 1) | |
} | |
connectedCallback() { | |
if (this.isConnected) { | |
this.btn = this.shadowRoot.querySelector('.dam-count-btn') | |
let n = this.getAttribute('count') | |
this.btn.textContent = `Count ${n}` | |
this.btn.addEventListener('click', this.updateCount) | |
} | |
} | |
} | |
customElements.define('dam-count', DamCount) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment