Last active
August 6, 2022 19:10
-
-
Save kristoferjoseph/31741efc6c5e2865f259e4af2d4a2248 to your computer and use it in GitHub Desktop.
CustomElement Base
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
export default class CustomElement extends HTMLElement { | |
constructor() { | |
super() | |
const templateName = `${this.tagName.toLowerCase()}-template` | |
const template = document.getElementById(templateName) | |
if (template) { | |
this.template = template | |
} | |
else { | |
this.template = document.createElement('template') | |
this.template.innerHTML = this.render({ html:this.html, state:{ attrs:{}, store:{} } }) | |
this.template.setAttribute('id', templateName) | |
} | |
this.render = this.render.bind(this) | |
this.beforeElUpdated = this.beforeElUpdated.bind(this) | |
this.replaceChildren(this.template.content.cloneNode(true)) | |
} | |
html(strings, ...values) { | |
const collect = [] | |
for (let i = 0; i < strings.length - 1; i++) { | |
collect.push(strings[i], values[i]) | |
} | |
collect.push(strings[strings.length - 1]) | |
return collect.join('') | |
} | |
render({ html, state={} }) { | |
const { attrs=[] } = state | |
const { greeting='Howdy' } = attrs | |
return html` | |
<h1>${ greeting }</h1> | |
` | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment