Last active
March 6, 2024 18:29
-
-
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
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
<!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/[email protected]/dist/index.js?module=true"; | |
import Store from "https://unpkg.com/@enhance/[email protected]/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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This example demonstrates how to use a single data store to orchestrate element data reactivity with multiple elements on a page.