Search code examples
custom-element

Custom elements: when to set up event listeners


The custom elements specification lists "Requirements for custom element constructors".

Herein, the last advisory statement is

In general, the constructor should be used to set up initial state and default values, and to set up event listeners and possibly a shadow root.

Now, regarding the life cycle of web components, removing a custom element from the DOM calls the disconnectedCallback lifecycle hook. To my understanding, this would be the point in time where I remove any event listeners added by the custom element.

Now, if I still hold a reference to that element, and at a later point, I put it back in the DOM, this will trigger the connectedCallback lifecycle hook.

And here's my problem: If it is advised to set up event listeners in the constructor rather than (properly guarded) in the connectedCallback, the re-introduced custom element will not receive its listeners, which were previously cleaned up by the disconnectedCallback.

I feel the add event listeners in the constructor advice - which I quoted from the spec - doesn't really go well together with the designed life cycle.

Are custom elements simply not meant to be removed from and later, reintroduced into the DOM?

Does anyone have reference as of how this is meant to be tackled? Is there some sort of best practice regarding the attaching and removing of listeners?


Solution

  • I tend to put my addEventListener calls in connectedCallback. Why do them before? The control is not in the DOM and you can not interact with it.

    I also put my removeEventListeners in disconnectedCallback. Sometimes I might even, when the internal DOM is complex, clear the internal DOM.

    There are a few components where I add addEventListener into the constructor, but:

    1. Only if it is for shadowDOM
    2. Only if I do not care to remove them myself since they will get cleaned up automatically when the internal DOM is destroyed by garbage collection.
    3. When I am just writing a simple test component

    But this is not something I do often. If there is any chance that my component might be added to and removed from the DOM, then I feel it must happen in connectedCallback and disconnectedCallback.