Skip to content

[idea] childConnectedCallback and childDisconnectedCallback #550

@trusktr

Description

@trusktr

I think having such methods would make it much easier than using MutationObserver for doing things when children are connected to a custom element.

Some reasons:

  • Suppose we wish to use connectedCallback to initiate a mutation observer, and disconnectedCallback to disconnect the observer, rather than initiating it in createdCallback or constructor. This has the side-effect that by the time connectedCallback is fired that the custom element may already have had children added to it, so the mutation observer won't catch those.

  • Using MutationObserver requires writing at least two nested for loops, which is much more verbose than simply placing logic inside a childConnectedCallback(child) method. f.e. compare

    connectedCallback() { // or perhaps in createdCallback or constructor?
        const observer = new MutationObserver(changes => {
            for (let change of changes) {
    
                for (let node of change.addedNodes) {
                    if (node instanceof MotorHTMLNode)
                        this.imperativeCounterpart.addChild(node.imperativeCounterpart)
                }
    
                for (let node of change.removedNodes) {
                    if (node instanceof MotorHTMLNode)
                        this.imperativeCounterpart.removeChild(node.imperativeCounterpart)
                }
    
            }
        })
        observer.observe(this, {
            childList: true
        })
    }

    vs

    childConnectedCallback(node) {
        this.imperativeCounterpart.addChild(node.imperativeCounterpart)
    }
    childDisconnectedCallback(node) {
        this.imperativeCounterpart.removeChild(node.imperativeCounterpart)
    }
  • The API is just easier, which is a good thing for people learning the Custom Element API.

On a similar note, it may be nice to have element-specific methods. For example (and as a possible alternative to my distributedCallback idea), HTMLSlotElement could have a childDistributedCallback(child) method, and it wouldbe possible to make a Custom Element that extends from HTMLSlotElement and to use it in place of the default <slot> element.

class MySlot extends HTMLSlotElement {
  childDistributedCallback(child) {
    console.log('Child distributed into this slot:', child)
  }
}

customElements.define('my-slot', MySlot)
<some-shadow-tree>
  <my-slot>
  </my-slot>
</some-shadow-tree>

I know we'll be able to use slotchange events, but the methods might be easier to work with.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions