Skip to content

Instantly share code, notes, and snippets.

@ashnur
Forked from WebReflection/todo.js
Created March 18, 2019 18:17
Show Gist options
  • Save ashnur/69c6a6b59e052a5a4f307689b7a4d5a2 to your computer and use it in GitHub Desktop.
Save ashnur/69c6a6b59e052a5a4f307689b7a4d5a2 to your computer and use it in GitHub Desktop.
Web Components, the React way, without Shadow DOM
// https://hackernoon.com/web-components-the-react-way-8ed5b6f4f942#.5em3zpgin
const store = (() => {
let state;
return todos => {
if (todos) {
state = todos;
render("todo-list");
}
return state;
};
})();
const render = (component, parent = document.body) =>
parent.innerHTML = `<${component}></${component}>`;
customElements.define("todo-item", class extends HTMLElement {
static get observedAttributes() {
return ["index"];
}
attributeChangedCallback(name, old, change) {
this.index = change;
}
connectedCallback() {
this.innerHTML = `
<label>
<input type=checkbox>
${this.innerHTML}
</label>
`;
this.querySelector("input").addEventListener("click", () =>
store(store().filter((todo, index) => index != this.index)));
}
});
customElements.define("todo-list", class extends HTMLElement {
connectedCallback() {
this.innerHTML = `
<ul>
${store().map((todo, index) => `
<li>
<todo-item index=${index}>
${todo}
</todo-item>
</li>
`).join("")}
</ul>
`;
}
});
store(["Buy milk", "Call Sarah", "Pay bills"]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment