How would you address your new found love?
class ClickButton extends HTMLElement {
constructor() {
super(); // Always call super() first
this.shadow = this.attachShadow({mode:'open'});
const buttonElement = document.createElement('button');
buttonElement.innerHTML = 'Click me';
const myButtonEl = this.shadow.appendChild(buttonElement);
myButtonEl.addEventListener('click', () => {
alert('Button clicked!');
});
this.button = buttonElement;
}
}
customElements.define('click-button', ClickButton);
or
customElements.define('click-button', class extends HTMLElement {
constructor() {
const createElement = (tag, props = {}) => Object.assign(document.createElement(tag), props);
super() // sets AND returns 'this'
.attachShadow({mode:'open'}) // sets AND returns this.shadowRoot
.append(
this.button = createElement( 'button', {
innerHTML: 'Click me',
onclick : (evt) => alert('Button clicked!', this.nodeName)
})
);
}
});
Top comments (4)
Both are fine, it's like the version with the anonymous class seems a particular case of the version with a named class. The named class example encourages convetions, further separation of concerns and it's better for longer web components.
However, the anonymous class has its advantages: registering the component on the bottom of the file plain sucks, because definition and registration are actually two separare things happening on the same file and you just discover it at the very end. Also, not being forced to name the class could be a slight advantage.
Most web components frameworks like Stencil and Lit look like the named class example but solve the annoying problem of registering happening on the bottom by using class decorators
Stencil does it like this
Lit does it like this
Good comments!
I'd love your review of: connect with the connectedCallback
Good to see back, Bruno
Personally I don't use SSR/SSG much. With the 10 to 40 KB I deliver and applications that require JavaScript anyway, there hardly is any benefit for me.
Getting scope right needs some extra work with
this.getRootNode()