Skip to content

Instantly share code, notes, and snippets.

@kristoferjoseph
Last active March 6, 2024 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kristoferjoseph/e3154183c596ccc001598dda3da1be6e to your computer and use it in GitHub Desktop.
Save kristoferjoseph/e3154183c596ccc001598dda3da1be6e to your computer and use it in GitHub Desktop.
Enhance element counter example using the store. Exposes the store via window.store. Update the count with window.store.count = 8
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<my-counter count=5></my-counter>
<my-increment click></my-increment>
<my-decrement click></my-decrement>
<script type="module">
import enhance from "https://unpkg.com/@enhance/element@1.4.2/dist/index.js?module=true";
import Store from "https://unpkg.com/@enhance/store@1.0.2/index.mjs?module=true";
//Initialize store
const store = Store({ count: 0 });
window.store = store
enhance("my-counter", {
// Define what keys on the store you want to listen to updates for
keys: ["count"],
store,
render({ html, state }) {
const { store = {} } = state;
const { count = 0 } = store;
// render the input with a count value from the store
return html`
<input value="${count}" />
`;
},
connected() {
// Use the count attribute to set the starting count per instance
this.store.count = Number(this.getAttribute("count"));
}
});
enhance("my-increment", {
store,
click() {
// Update the count in the store to trigger an update
this.store.count = this.store.count + 1;
},
render({ html, state }) {
return html`
<button>+</button>
`;
}
});
enhance("my-decrement", {
store,
click() {
// Update the count in the store to trigger an update
this.store.count = this.store.count - 1;
},
render({ html, state }) {
return html`
<button>-</button>
`;
}
});
</script>
</body>
</html>
@kristoferjoseph
Copy link
Author

This example demonstrates how to use a single data store to orchestrate element data reactivity with multiple elements on a page.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment