Skip to content

Instantly share code, notes, and snippets.

@Punk-UnDeaD
Last active August 9, 2019 07:43
Show Gist options
  • Save Punk-UnDeaD/4192e0f07fb8b9fd46521d4c2724b11c to your computer and use it in GitHub Desktop.
Save Punk-UnDeaD/4192e0f07fb8b9fd46521d4c2724b11c to your computer and use it in GitHub Desktop.
class BindedTemplate extends HTMLTemplateElement {
processTokens() {
return this._tokens.map((token) => {
token = token.substr(2, token.length - 3);
let not = token[0] === '!';
let notnot = not && token[1] === '!';
if (not) {
token = token.substr(not + notnot);
}
let value = token.split('.').reduce((value, subtoken) => {
let f_arg = subtoken.match(/(.+)\((.*)\)/);
if (f_arg) {
f_arg[2] = f_arg[2].split(/\s*,\s*/);
return value[f_arg[1]](...f_arg[2]);
}
else {
return value[subtoken];
}
}, this.context);
switch (true) {
case notnot: return !!value;
case not: return !value;
default: return value;
}
});
}
render() {
const {render, html} = lighterhtml;
render(this._child, () => html(this._html_chunks, ...this.processTokens()));
}
connectedCallback() {
const re = /\$\{[^\}]+\}/g;
this._html_chunks = this.innerHTML.split(re);
this._tokens = this.innerHTML.match(re);
this._child = document.createDocumentFragment();
this.render();
this.parentElement.insertBefore(this._child, this);
}
}
customElements.define('d-app-bind', class extends BindedTemplate {
connectedCallback() {
const dUser = document.querySelector('d-user');
this.context = {user: dUser.user};
super.connectedCallback();
dUser.addEventListener('user.update', () => {
this.context.user = dUser.user;
this.render();
})
}
}, {extends: 'template'});
<template is="d-app-bind">
<li hidden=${!user.isAuthenticated}>
<a href=${user.logoutLink()}>Exit</a>
</li>
</template>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment