A simple HTML in Javascript implementation featuring Model View Binding. It allows you to create HTML elements using template literals and bind them to your model.
npm install --save @dobschal/html.jsThe example below creates a simple div element with the text "Hello World" and appends it to the body.
import{html}from'@dobschal/html.js';document.body.append(html`<div>Hello World</div>`);The created view is bound to the count observable. When the count changes, the view is updated:
import{html}from'@dobschal/html.js';import{Observable}from'@dobschal/observable';constcount=Observable(0);constview=html`<p>👉 ${count}</p><buttononclick="${()=>count.value++}">Count Up 🚀</button>`;document.body.append(...view);Example for binding input values:
constname=Observable("Sascha");constview=html`<p>👉 ${name}</p><inputtype="text" value="${name}" />`;html is a tagged template literal function that creates an HTML element or elements from a template string.
// Create a div element with the text "Hello World"constelement=html`<div>Hello World</div>`;console.log(elementinstanceofHTMLElement);// trueIn case the HTML template contains multiple elements, an array of elements is returned! When appending to the DOM, you can use the spread operator to append all elements at once.
document.body.append(...html`<div>Hello World 1</div><div>Hello World 2</div>`);You can create components by defining a function that returns an HTML element.
functionMyComponent(){returnhtml`<div>Hello World</div>`;}functionApp(){returnhtml`<div>${MyComponent()}</div> `;}document.body.append(App());You can add event listeners to elements by using the standard HTML event attributes.
html`<buttononclick="${()=>console.log('Clicked')}">Click Me</button>`;You can bind an observable to an element by using the observable directly in the template.
import{Observable}from'@dobschal/observable';constcount=Observable(0);constview=html`<p>👉 ${count}</p><buttononclick="${()=>count.value++}">Count Up 🚀</button>`;You can conditionally render elements by using the ternary operator or the custom if attribute.
constshow=Observable(true);// With the ternary operatorconstview=html`${show ? html`<div>Hello World</div>` : null}`;// With the if attributeconstview=html`<divif="${show}">Hello World</div>`;You can render lists by using the map function on an array or observable array.
constitems=Observable([1,2,3]);constview=html`<ul>${items.map(item=>html`<li>${item}</li>`)}</ul>`;Sascha Dobschal