Lifecycle call
The specification for custom elements logs a series of lifecycle callbacks, functions which run at specific points in the element’s existence. These are only a handful, and important enough to warrant a quick repetition.
constructor
The element is created.
While technically not a callback, the function is your first stop to initialize the node.
For the sake of argument, if you were to fabricate a custom element with a valid, hyphenated name.
<hey-listen></hey-listen> It is in the constructor function that you can inherit the feature of a class such as HTMLElement.
class HeyListen extends HTMLElement {
constructor() {
super();
}
} And it is always in the constructor where you can structure the content with proper markup. Perhaps even through the shadow DOM.
const shadowRoot = this.attachShadow({ mode: 'open' });
shadowRoot.innerHTML = ``; connectedCallback
The element is inserted in the DOM.
As the element finds its place in the larger document, the function is the best place to complete the component in terms of functionality. Here you tend to listen to particular events, and perhaps interact with the APIs available on the web.
connectedCallback() {
this.interval = setInterval(() => {
// something mildly annoying
}, 2000);
} disconnectedCallback
The element is removed from the DOM.
On the opposite end of connectedCallback, the function is a good place to clean up the code, removing event listeners and those pesky operations persisting in the DOM.
disconnectedCallback() {
clearInterval(this.interval);
} attributeChangedCallback
An attribute changes. Or, to be precise, an observed attribute changes.
Just like regular HTML nodes, custom elements benefit from key-value pairs in the opening tag.
<hey-listen spirit="courage"></hey-listen> Should you update, add or remove an attribute.
const heyListen = document.querySelector('hey-listen');
heyListen.setAttribute('spirit', 'wisdom'); You can thank the function to detect the change.
attributeChangedCallback(name, oldValue, newValue) {
// do something and keep going
} As long as you set up the custom element to keep a watchful eye on the attribute through a getter function, observedAttributes.
static get observedAttributes() {
return ['spirit'];
} Keeping attributes up-to-date is slightly more complicated, but when you want to synchronize the values between element and class, it is more than worth learning.
adoptedCallback
The element is moved to a new document.
Through the document global, the adoptNode function lets you move an element between documents. The operation is fairly confounding, might involve an iframe, and for the life of me, still lacks a use-case.
You can rest assured, however, even without the specific mention, there’s plenty you can achieve with the existing functions.