Skip to content

Instantly share code, notes, and snippets.

@talentlessguy
Created February 4, 2019 22:22
Show Gist options
  • Save talentlessguy/c1ee1026f2182efef25a4aa89853383a to your computer and use it in GitHub Desktop.
Save talentlessguy/c1ee1026f2182efef25a4aa89853383a to your computer and use it in GitHub Desktop.
Web components
const { log } = console
class App extends HTMLElement {
constructor() {
super()
this.onclick = e => this.sayHello()
}
sayHello() {
this.textContent = 'Hello World'
}
connectedCallback() {
log('Element connected!')
}
disconnectedCallback() {
log('Element disconnected!')
}
static get observedAttributes() {
return ['prop']
}
attributeChangedCallback(attr, prev, next) {
if (prev !== null) {
log('Attribute changed from ' + prev + ' to ' + next)
}
else log('Attribute found: ' + attr)
}
}
const hide = () => {
document.querySelector('sample-app').remove()
}
const change = () => {
document.querySelector('sample-app').setAttribute('prop', 'newVal')
}
customElements.define('sample-app', App)
<!DOCTYPE html>
<html>
<head>
<!-- Polyfill -->
<script src="https://unpkg.com/built-in-element"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<style>
button {
display: block;
}
sample-app {
font-size: 30px;
font-weight: bold;
}
</style>
</head>
<body>
<script src="app.js"></script>
<sample-app prop="hi">Hi</sample-app>
<button onclick="hide()">Hide sample-app</button>
<button onclick="change()">Change attributes </button>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment