-
Notifications
You must be signed in to change notification settings - Fork 386
Description
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
connectedCallbackto initiate a mutation observer, anddisconnectedCallbackto disconnect the observer, rather than initiating it increatedCallbackorconstructor. This has the side-effect that by the timeconnectedCallbackis 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. compareconnectedCallback() { // 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.