0

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?

Chris Hansen
  • 7,813
  • 15
  • 81
  • 165
  • It's a little unclear to me what the exact question is. An event listener can be added in connectedCallback with `addEventListener`. In the constructor code you can clean up the `ccx-comments-loaded` event handler by passing an options object with [`once: true`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#:~:text=to%20false.-,once,-Optional). The question of waiting until rendering is complete before dispatching an event is covered in the [`updateComplete` documentation](https://lit.dev/docs/components/lifecycle/#updatecomplete). – YouCodeThings Oct 18 '22 at 19:08

2 Answers2

0

Store a reference to the Event Listener, then remove it in the disconnectedCallback

customElements.define("my-element", class extends HTMLElement {
  constructor() {
    super();
    this.listener = window.addEventListener("click", () => {
      this.remove();
    });
  }
  connectedCallback() {
    this.innerHTML = `Listening! Click to remove Web Component`;
  }
  disconnectedCallback() {
    // element is no longer in the DOM; 'this' scope still available!!!
    window.removeEventListener("click", this.listener);
    document.body.append("Removed Web Component and Listener");
  }
})
<my-element></my-element>
Danny '365CSI' Engelman
  • 16,526
  • 2
  • 32
  • 49
0

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.

Max Larionov
  • 420
  • 6
  • 19