Component with Script
A component may be composed of three parts: template, style and script. None of them are required.
<component name="badge-number" extends="span"><template></template><style></style><script></script></component>
Until now we saw template and style. Let's get started with <script>
.
HTML Custom Elements must be registered with a class inheriting from an existing element class, such as HTMLElement.
The script tag must contain a class with the same name of the component but written in CamelCase.
The following example shows the component's class implementing the connectedCallback method which is part of the lifecycle from web components. This method is called once the component is appended to the DOM.
<component name="my-title" extends="h1"><style>h1 {background-color: rgb(145, 64, 64);padding: 10px;border-radius: 8px;cursor: pointer;}</style><script>class MyTitle extends HTMLElement {connectedCallback() {this.h1 = this.shadowRoot.querySelector('h1')this.h1.addEventListener('click', this.change)}change = () => {this.h1.innerText = this.getAttribute('new-text')this.h1.style.backgroundColor = 'green'}}</script></component><my-title new-text="good!">Click me</my-title><my-title new-text="bye!">Click me</my-title>