简体   繁体   中英

Dispatching event on disconnectedCallback

Is there a way to dispatch an event when an element is removed? I tried the following:

class MyElement extends LitElement {
  constructor() {
    super();

    this.addEventListener('child-removed', this._handleChildRemoved);
  }

  render() {
    return html`
      <my-child-element></my-child-element>
    `;
  }

  _handleChildRemoved() {
    console.log('child removed!');
  }
}

class MyChildElement extends LitElement {
  disconnectedCallback() {
    super.disconnectedCallback();

    console.log('removed');

    this.dispatchEvent(new CustomEvent('child-removed', {
      bubbles: true,
      composed: true,
    }));
  }
  
  render() {
    return html`
      <p>Child</p>
      <button @click=${this._handleClick}>X</button>
    `;
  }

  _handleClick() {
    this.remove();
  }
}

console.log('removed'); is called but console.log('child removed'); is not called.

For full details see: https://github.com/WICG/webcomponents/issues/678

In this use-case: your _handleClick method does the remove,
so put the dispatchEvent there, before you call this.remove() .

The disconnectedCallback is for clean-up,
the element itself is already removed and can't perform DOM actions,
as you can see with: console.log("removed",this.innerHTML)

While there may be a way to engineer this behaviour using event emitters, I believe the recommended pattern for this behaviour is to pass a function from the parent to the child component as a prop. This function can remove the child. So the source of truth is the parent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM