Last active
July 9, 2020 21:28
-
-
Save thawkin3/c1de9c89f254421ff352bb713a2df0bc to your computer and use it in GitHub Desktop.
Native Web Component Example
This file contains 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
class MyCounter extends HTMLElement { | |
constructor() { | |
super(); | |
this.count = 0; | |
const style = ` | |
* { | |
font-size: 200%; | |
} | |
span { | |
width: 4rem; | |
display: inline-block; | |
text-align: center; | |
} | |
button { | |
width: 64px; | |
height: 64px; | |
border: none; | |
border-radius: 10px; | |
background-color: seagreen; | |
color: white; | |
} | |
`; | |
const html = ` | |
<button id="dec">-</button> | |
<span>${this.count}</span> | |
<button id="inc">+</button> | |
`; | |
this.attachShadow({ mode: 'open' }); | |
this.shadowRoot.innerHTML = ` | |
<style> | |
${style} | |
</style> | |
${html} | |
`; | |
this.buttonInc = this.shadowRoot.getElementById('inc'); | |
this.buttonDec = this.shadowRoot.getElementById('dec'); | |
this.spanValue = this.shadowRoot.querySelector('span'); | |
this.inc = this.inc.bind(this); | |
this.dec = this.dec.bind(this); | |
} | |
inc() { | |
this.count++; | |
this.update(); | |
} | |
dec() { | |
this.count--; | |
this.update(); | |
} | |
update() { | |
this.spanValue.innerText = this.count; | |
} | |
connectedCallback() { | |
this.buttonInc.addEventListener('click', this.inc); | |
this.buttonDec.addEventListener('click', this.dec); | |
} | |
disconnectedCallback() { | |
this.buttonInc.removeEventListener('click', this.inc); | |
this.buttonDec.removeEventListener('click', this.dec); | |
} | |
} | |
customElements.define('my-counter', MyCounter); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment