UNPKG

joicomponents

Version:

Design patterns to build native web components

72 lines (65 loc) 2.46 kB
<script> class GreenFrame extends HTMLElement { constructor(){ super(); this.attachShadow({mode: "open"}); this.shadowRoot.innerHTML = `<style> div { display: block; border: 10px solid green; } </style> <div> <slot id="hasFallback"><h3>You can put stuff here)</h3></slot> </div>`; this.shadowRoot.addEventListener("slotchange", function(e){ console.log("A slotchange event has occured!"); console.log("The slot's id is:", e.target.id); console.log("The slot contains:", e.target.assignedNodes({flatten: true})); }); } } customElements.define("green-frame", GreenFrame); </script> <green-frame id="one"></green-frame> <green-frame id="two"><h1>Hello world!</h1></green-frame> <!--3--> <script> const first = document.querySelector("green-frame"); const firstSlot = first.shadowRoot.children[1].children[0]; console.log("-------------"); console.log("The empty slot contains:", firstSlot.assignedNodes({flatten: true})); console.log("-------------"); setTimeout(function(){ const h2 = document.createElement("h2"); h2.innerText = "Stay green!"; document.querySelector("green-frame#two").appendChild(h2); }, 2000); setTimeout(function(){ const h1 = document.querySelector("h1"); document.querySelector("green-frame#two").appendChild(h1); }, 4000); </script> <ol> <li> In the console, you will first see one slotchange event being processed. This is the slotchange event for the "Hello world!" text. There is no slotchange event for fallback nodes, but there is a slotchange event when nodes are transposed into an element when the element is first declared. </li> <li> After the initial slotchange event, you will see the content of the slot with the fallback nodes being logged. </li> <li> After 2000ms, you will see a second slotchange event. This slotchange event occurs as second node is appended in the lightDOM and then transposed into the green-frame shadowDOM. </li> <li> After 4000ms, you will see a third slotchange event. This slotchange event occurs as the order of the transposed nodes change. </li> <li> In Safari browsers (IOS todo), the initial slotchange event is *not* dispatched. This is a bug in the old Safari browsers. </li> </ol>