Skip to content

Instantly share code, notes, and snippets.

@jsmithdev
Last active June 9, 2022 04:49
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jsmithdev/59ab24927cb385fc780d3860cc01790d to your computer and use it in GitHub Desktop.
Save jsmithdev/59ab24927cb385fc780d3860cc01790d to your computer and use it in GitHub Desktop.
Web Component boilerplate for a native web-component (v1 spec)
/*
* Use tag to import via es6 module (html import deprecated in v1 spec :/ )
* <script type="module" src="../components/web-component/web-component.js"></script>
*/
'use strict()'
const template = document.createElement('template')
template.innerHTML = /*html*/`
<style>
.card {
padding: 1rem;
border-radius: 5px;
max-width: 100%;
min-height: 20rem;
background: #EEE;
}
</style>
<div class="card">
<h3>Example DOM</h3>
<input class="name" placeholder="Name"/>
<br />
<button class="save">Save</button>
</div>`
export class WebComponent extends HTMLElement {
constructor() {
super()
//console.log('hi from constructor')
this.attachShadow({mode: 'open'})
}
static get is() {
return 'web-component'
}
static get observedAttributes() {
return ['projects']
}
connectedCallback() {
this.shadowRoot.appendChild(template.content.cloneNode(true))
this.registerElements(this.shadowRoot)
}
registerElements(doc){
//console.log('registerElements')
this.dom = {
name: doc.querySelector('.name'),
save: doc.querySelector('.save')
}
this.registerListeners()
}
registerListeners(){
this.dom.save.onclick = () => {
console.log('CLICK ', this.dom.name.value)
}
}
attributeChangedCallback(n, ov, nv) {
super.attributeChangedCallback(n, ov, nv);
console.dir(n)
console.dir(ov)
console.dir(nv)
//switch (n) {
// case 'attr name that changed!':
// ov !== nv // old val not equal new val
// break;
//}
}
}
customElements.define(WebComponent.is, WebComponent)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment