Last active
August 15, 2019 20:58
-
-
Save mjstahl/74477813b06e20150aa4a9f9cf0ba818 to your computer and use it in GitHub Desktop.
Trying out web components
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
class HelloThing extends HTMLElement { | |
static get observedAttributes () { | |
return ['thing'] | |
} | |
constructor () { | |
super() | |
this.attachShadow({ mode: 'open' }) | |
this.render() | |
} | |
get thing () { | |
return this.getAttribute('thing') | |
} | |
set thing (value) { | |
this.setAttribute('thing', value) | |
} | |
render () { | |
const template = document.createElement('template') | |
template.innerHTML = ` | |
<style> | |
:host { | |
color: darkgreen; | |
} | |
</style> | |
<h1>Hello | |
<span id="thing">${this.thing}</span> | |
</h1> | |
` | |
this.shadowRoot.appendChild(template.content.cloneNode(true)) | |
} | |
attributeChangedCallback (name, oldValue, newValue) { | |
this.shadowRoot.getElementById(name).innerText = newValue | |
} | |
} | |
customElements.define('hello-thing', HelloThing) |
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> | |
<head> | |
<script type="module" src="hello-thing.js"></script> | |
</head> | |
<body> | |
<hello-thing thing="World"></hello-thing> | |
<input id="thing" type="text" value="World" /> | |
<button id="set-thing" type="submit">Set Thing</button> | |
<script type="module"> | |
const button = document.querySelector('#set-thing') | |
const element = document.querySelector('hello-thing') | |
const input = document.querySelector('#thing') | |
button.onclick = () => element.thing = input.value | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment