How to detect when an Custom Element's is tran

2019-08-15 04:45发布

问题:

A Custom Element's attachedCallback can be used to detect an element's original insertion point by looking at, but how do we detect it's final resting point once it has been transcluded into shadow DOM (for example placed inside a <content> or soon <slot> element)?

I'm thinking something like a "slottedCallback" which doesn't currently exist.

For extra details on why I (might) need this, see https://github.com/w3c/webcomponents/issues/504

EDIT: Answering @Supersharp's question:

did you try getDistributedNodes()?

Based on the way ShadowDOM is supposed to be used, it means I can create a Custom Element, and some other person can transclude my Custom Element into their ShadowDOM without me knowing. I don't think I have access to that other person's ShadowDOM (ShadowDOM is meant to be encapsulated), therefore I cannot call getDistributedNodes() on a <slot> element in that other person's ShadowDOM because I don't (and should not) have access to it. The problem is that I need to know when my Custom Element is transcluded ("distributed") into some other ShadowDOM so that my Custom Element can decide if it has been distributed into a pre-defined set of allowable target elements (i.e. it needs to throw an error if it is distributed into an invalid element).

In order for the above to be possible, my Custom Element needs to know when it has been distributed (not just attached). It seems that current the attachedCallback only fires when my Custom Element is attached into an element in the "light DOM", but Custom Elements currently have no way of knowing when they are transcluded/distributed.