[w3c/webcomponents] [idea] childConnectedCallback and childDisconnectedCallback (#550)

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
  ```js
  connectedCallback() { // or perhaps in createdCallback or constructor
      const observer = new MutationObserver(changes => {
          console.log('Child added!', 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
  ```js
  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`](https://github.com/w3c/webcomponents/issues/527) 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.

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

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

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/w3c/webcomponents/issues/550

Received on Monday, 22 August 2016 05:12:32 UTC