[w3c/webcomponents] [idea] distributedCallback (#527)

There's currently no way for an HTMLElement to know when it gets distributed into a content or slot elements. In v1 API, there is a new `slotchange` event, but this is only useful to the parent of the slot element. In a closed tree, children can get references to the slot they are distributed into.

So how can an element know when it is distributed?

Maybe there can be a `distributedCallback` that Custom Element classes can define. The `distributedCallback`can receive a single argument: `slot`. The `slot` argument is a reference to the slot where the element got distributed into. If the tree that the element was distributed into is closed, then the value of the slot argument can be null. Additionally, `slotchange` handlers should be executed before `distributedCallback`s.

For exampe:

```js
class MyElement extends HTMLElement {
  distributedCallback(slot) {
    console.log(slot)
  }
}

customElements.define('my-element', MyElement)
```

If it is a guarantee that `slotchange` events on the receiving slot element fires before `distributedCallback` of the elements being distributed, then we can do some nifty things. For example, it would solve the problem I have in https://github.com/w3c/webcomponents/issues/504#issuecomment-228502080.

In my case (and I can see this also applying to any other libraries made of Custom Elements like http://aframe.io), I need to detect when element of type A is distributed into another element of type A.

If parent element A contains a slot, it can watch for `slotchange` events in order to detect distributed child elements also of type A, and the parent A element can then establish a connection with the child A element.

However, I need to detect the case where a child elelement A is distributed into another element that is not of type A, and I want to throw an error. This is currently not possible because the child element A does not know that it has been distributed, and even if it did, it cannot see the parent of the slot element that contains it if the shadow tree is closed.

So, if we can guarantee that `slotchange` fires before child `distributeCallbacks`, then in the distributedCallback of a child A that was distributed into any other element that is not of type A, the child A element will notice that a connection has not been made, and can make the safe assumption that it has not been distributed properly into another element of type A, and an error can be thrown.

---
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/527

Received on Saturday, 25 June 2016 02:40:40 UTC