Created
August 6, 2017 18:09
-
-
Save enjikaka/c199f86a462c34340cc362858fdb18df to your computer and use it in GitHub Desktop.
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
| <script> | |
| /** | |
| * Component that automagically finds sibling <template> | |
| * to the instance script and uses it for rendering, with | |
| * out without the getState form the instace of the child. | |
| * | |
| * @class TemplateComponent | |
| * @extends {HTMLElement} | |
| */ | |
| class TemplateComponent extends HTMLElement { | |
| constructor (tagName) { | |
| super(); | |
| if (!tagName) { | |
| throw new Error('You did now specify a tag name. You need to call super with the tag name in you constructor.'); | |
| } | |
| this._tagName = tagName; | |
| } | |
| connectedCallback () { | |
| this.render(); | |
| } | |
| get path () { | |
| const query = `link[rel="import"][href*="${this._tagName}"]`; | |
| const target = document.head.querySelector(query); | |
| return target.href.split(document.location.host)[1]; | |
| } | |
| async getTemplate (data) { | |
| const templator = (t, d) => new Function('return `' + t + '`').call(d); // eslint-disable-line no-new-func | |
| return await fetch(this.path) | |
| .then(r => r.text()) | |
| .then(markup => { | |
| let templateContent = markup.split('<template>')[1].split('</template>')[0]; | |
| if (data) { | |
| templateContent = templator(templateContent, data); | |
| } | |
| return `<template>${templateContent}</template>`; | |
| }) | |
| .then(templateMarkup => { | |
| const el = document.createElement('div'); | |
| el.innerHTML = templateMarkup; | |
| return el.querySelector('template'); | |
| }) | |
| .catch(console.error); | |
| } | |
| async render () { | |
| let state; | |
| if (this.getState) { | |
| state = await this.getState(); | |
| } | |
| const template = await this.getTemplate(state); | |
| const shadowDOM = this.attachShadow({ mode: 'open' }); | |
| const clone = document.importNode(template.content, true); | |
| this._shadowDOM = shadowDOM; | |
| shadowDOM.appendChild(clone); | |
| if (this.postRender) { | |
| this.postRender(); | |
| } | |
| } | |
| } | |
| </script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment