Where are lifecycle callbacks defined?

154 Views Asked by At

I'm learning about custom elements, and I see that in the class definition we can use these methods, the lifecycle callbacks. But I'm a bit confused about how they work. The reason I'm confused is because they're methods, with a particular name, similar to constructor, but in difference to constructor, they're not defined by the standard. So, where, and how are they defined, in order to be connected with the DOM?

I checked the HTMLElement's prototype, from which custom elements inherit, but it doesn't contain any methods such as connectedCallback, adoptedCallback, etc. I think they must work something like keywords do, but I'm not sure.

I've read somewhere mentioning web hooks, but didn't understand that. To me, they seem like they have the same functionality to events. So, why don't we use events instead?

1

There are 1 best solutions below

0
On

These callbacks are set at the step 14.4.1 of the CustomElementRegistry#define() method algorithm:

  1. Let lifecycleCallbacks be a map with the keys "connectedCallback", "disconnectedCallback", "adoptedCallback", and "attributeChangedCallback", each of which belongs to an entry whose value is null.

  2. For each of the keys callbackName in lifecycleCallbacks, in the order listed in the previous step:

    1. Let callbackValue be ? Get(prototype, callbackName).

    2. If callbackValue is not undefined, then set the value of the entry in lifecycleCallbacks with key callbackName to the result of converting callbackValue to the Web IDL Function callback type. Rethrow any exceptions from the conversion.