Skip to content

Instantly share code, notes, and snippets.

@kristoferjoseph
Created March 6, 2024 17:28
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/56050518f6b94ca7754666664662da60 to your computer and use it in GitHub Desktop.
Save kristoferjoseph/56050518f6b94ca7754666664662da60 to your computer and use it in GitHub Desktop.
Counter component using Enhance element and attributes
<!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>
<script type="module">
import enhance from "https://unpkg.com/@enhance/element@1.4.2/dist/index.js?module=true";
enhance("my-counter", {
attrs: ['count'],
render({ html, state }) {
const { attrs = {} } = state;
const { count = 0 } = attrs;
// render the input with a count value from the store
return html`
<input value="${count}" />
<button aria-label="decrement">-</button>
<button aria-label="increment">+</button>
`;
},
connected() {
// Use the count attribute to set the starting count per instance
this.count = Number(this.getAttribute("count"))
this.increment = this.querySelector('[aria-label=increment]')
this.increment.addEventListener('click', e => {
this.count = this.count + 1
this.setAttribute('count', this.count)
})
this.decrement = this.querySelector('[aria-label=decrement]')
this.decrement.addEventListener('click', e => {
this.count = this.count - 1
this.setAttribute('count', this.count)
})
}
});
</script>
</body>
</html>
@kristoferjoseph
Copy link
Author

This example demonstrates how to use attributes and state to enable data reactivity with a single element.

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