Skip to content

Instantly share code, notes, and snippets.

@mjstahl
Last active August 15, 2019 20:58
Show Gist options
  • Save mjstahl/74477813b06e20150aa4a9f9cf0ba818 to your computer and use it in GitHub Desktop.
Save mjstahl/74477813b06e20150aa4a9f9cf0ba818 to your computer and use it in GitHub Desktop.
Trying out web components
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)
<!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