Search code examples
lit-elementlit

how to add an event listener in connectCallback


I want to wait until elements are rendered in the dom to dispatch an event. I have a lit element that is wrapped around a react element.

In the connectedCallback I have the following

connectedCallback() {
    super.connectedCallback();
    CommentsManager.register(this);

    const event = new Event('ccx-comments-loaded');
    window.dispatchEvent(event);
}

in the constructor, I have the following

this.isReadyPromise = new Promise(function(resolve, reject) {
    window.addEventListener('ccx-comments-loaded', () => {
        resolve(true);
    });
});

How can I remove the listener that I created?


Solution

  • I want to wait until elements are rendered in the dom to dispatch an event.

    This looks like you could use an already existing updateComplete method from lit-element lifecycle. It is executed after render and it sounds like you may want to use it instead of having your own events. You could read more about it here: https://lit.dev/docs/v1/components/lifecycle/#updatecomplete

    This would be a clean and more straightforward way to use lit-element. This way you don't reinvent something existing and your code would be more straightforward and clear for the other developers.