chore: update examples

This commit is contained in:
Ayo 2023-09-17 00:00:22 +02:00
parent f8a71c22c8
commit 9b10824928
3 changed files with 26 additions and 26 deletions

View file

@ -1,6 +1,8 @@
# Web Component Base Class
# Web Component Base
This is a base JavaScript class for creating Web Components easily.
This serves as a very minimal base class for creating custom elements.
This does not aim to be an alternative to [Lit](https://lit.dev/). Lit is good; use it if you want.
## Installation
@ -12,6 +14,8 @@ npm i web-component-base
When you extend the `WebComponent` class for your component, you only have to define the `template()` and `observedAttributes()`, and the UI will be reactive on attribute changes.
In your component class:
```js
// HelloWorld.mjs
import { WebComponent } from "./WebComponent.mjs";
@ -29,22 +33,23 @@ export class HelloWorld extends WebComponent {
<h1>Hello ${this.name}${this.emotion === "sad" ? ". 😭" : "! 🙌"}</h1>`;
}
}
customElements.define('hello-world', HelloWorld);
```
Then changes in the attributes observed will cause the UI to render.
In your HTML page:
```html
<head>
...
<script type="module">
import {HelloWorld} from './HelloWorld.mjs';
customElements.define('hello-world', HelloWorld);
</script>
<script type="module" src="HelloWorld.mjs"></script>
</head>
<body>
<hello-world name="Ayo" emotion="sad">
<script>
const helloWorld = document.querySelector('hello-world');
setTimeout(() => {
helloWorld.setAttribute('emotion', 'excited');
}, 2500)
@ -52,4 +57,6 @@ Then changes in the attributes observed will cause the UI to render.
</body>
```
<img alt="UI showing feeling toward Web Components changing from SAD to EXCITED" src="https://git.sr.ht/~ayoayco/web-component-base/blob/main/assets/wc-feeling.gif" width="500" />
The result is a reactive UI that updates on attribute changes:
<img alt="UI showing feeling toward Web Components changing from SAD to EXCITED" src="https://git.sr.ht/~ayoayco/web-component-base/blob/main/assets/wc-base-demo.gif" width="400" />

View file

@ -18,3 +18,5 @@ export class HelloWorld extends WebComponent {
}</h1>`
}
}
customElements.define('hello-world', HelloWorld);

View file

@ -1,21 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello World WC</title>
<script type="module">
import {HelloWorld} from './HelloWorld.mjs';
customElements.define('hello-world', HelloWorld);
</script>
<script type="module" src="HelloWorld.mjs"></script>
</head>
<body>
<hello-world name="Ayo" emotion="sad" />
<script>
const helloWorld = document.querySelector('hello-world');
setTimeout(() => {
helloWorld.setAttribute('emotion', 'excited');
}, 2500)
</script>
<hello-world name="Ayo" emotion="sad">
<script>
const helloWorld = document.querySelector('hello-world');
setTimeout(() => {
helloWorld.setAttribute('emotion', 'excited');
}, 2500)
</script>
</body>
</html>