Created
November 1, 2021 09:22
-
-
Save crutchcorn/8d8c5df2f64ec0c8005d1497fefb67bb to your computer and use it in GitHub Desktop.
This file contains 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> | |
// Base.js | |
class OurBaseComponent extends HTMLElement { | |
connectedCallback() { | |
this.doRender(); | |
} | |
createState(obj) { | |
return Object.keys(obj).reduce((prev, key) => { | |
// This introduces bugs | |
prev["_" + key] = obj[key]; | |
prev[key] = { | |
get: () => prev["_" + key], | |
set: (val) => this.changeData(() => prev["_" + key] = val); | |
} | |
}, {}) | |
} | |
changeData(callback) { | |
callback(); | |
this.clear(); | |
this.doRender(); | |
} | |
clear() { | |
for (const child of this.children) { | |
child.remove(); | |
} | |
} | |
doRender(callback) { | |
this.clear(); | |
callback(); | |
} | |
} | |
</script> | |
<script> | |
// MainFile.js | |
class MyComponent extends OurBaseComponent { | |
state = createState({todos: []}); | |
render() { | |
this.doRender(() => { | |
this.innerHTML = `<h1>You have ${this.state.todos.length} todos</h1>` | |
}) | |
} | |
} | |
customElements.define('my-component', MyComponent); | |
</script> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment