Skip to content Skip to sidebar Skip to footer

How Deal "connectedcallback May Be Called Once Your Element Is No Longer Connected" Coding A Webcomponent

That statement pasted in my question was copied from https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements#Using_the_lifecycle_callbacks. As a no-experi

Solution 1:

The only case when connectedCallback() is called after the Custom Element is disconnected is when you play with it: moving it or removing it very quickly after it is created could sometimes lead to this situation.

In your described use case, if you're using a persistent, single page application to host your Web Component, this will never happen. Actually your Custom Element will never be disconnected, until the page is closed.

Solution 2:

In addition to what @supersharp has said I will add one other thing:

Do not call attachShadow in connectedCallback:

Your code:

classInputKafkaextendsHTMLElement {
  connectedCallback() {
    this.attachShadow({mode: 'open'})
    this.shadowRoot.appendChild(template.content.cloneNode(true))
    const inputKafka = this.shadowRoot.getElementById('inputKafka');

    const source = newEventSource('http://localhost:5000/kafka_sse');
    source.addEventListener('sendMsgFromKafka', function(e) {
      console.log('fromKafka');
      inputKafka.value = e.data;
    }, false);
  }
}

Your code should call attachShadow in the constructor

classInputKafkaextendsHTMLElement {
  constructor() {
    super();
    this.attachShadow({mode: 'open'})
    this.shadowRoot.appendChild(template.content.cloneNode(true))
    const inputKafka = this.shadowRoot.getElementById('inputKafka');

    const source = newEventSource('http://localhost:5000/kafka_sse');
    source.addEventListener('sendMsgFromKafka', function(e) {
      console.log('fromKafka');
      inputKafka.value = e.data;
    }, false);
  }
}

Otherwise you will be attempting to create a new shadowRoot every time your component is attached to the body. Yes, your code may not do that, but always write your code assuming that someone will attach, remove and re-attach.

If you are not using shadowDOM then you will want to wait until connectedCallback is called to add your child elements as specified in the Requirements for Custom Element Constructors.

I either create my child elements one time, if they are complex, or every time the component is connected, when a property changes or when an attribute changes.

Post a Comment for "How Deal "connectedcallback May Be Called Once Your Element Is No Longer Connected" Coding A Webcomponent"