Skip to content

Instantly share code, notes, and snippets.

@kristoferjoseph
Last active August 6, 2022 19:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kristoferjoseph/31741efc6c5e2865f259e4af2d4a2248 to your computer and use it in GitHub Desktop.
Save kristoferjoseph/31741efc6c5e2865f259e4af2d4a2248 to your computer and use it in GitHub Desktop.
CustomElement Base
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