Created
March 21, 2020 15:33
-
-
Save ademilter/1ed7cea4cfa97912c05d092da88037ca to your computer and use it in GitHub Desktop.
web component example
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
const template = document.createElement('template') | |
template.innerHTML = ` | |
<style> | |
.red { | |
color: red; | |
} | |
</style> | |
<div class="red"> | |
<p>Hey</p> | |
<button type="button">click</button> | |
</div> | |
` | |
class MyElement extends HTMLElement { | |
constructor () { | |
super() | |
this.attachShadow({ mode: 'open' }) | |
this.shadowRoot.appendChild(template.content.cloneNode(true)) | |
} | |
connectedCallback () { | |
this.shadowRoot.querySelector('button') | |
.addEventListener('click', () => console.log('click')) | |
} | |
disconnectedCallback () { | |
this.shadowRoot.querySelector('button') | |
.removeEventListener() | |
} | |
} | |
customElements.define('my-element', MyElement) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment