Re: [WICG/webcomponents] HTML Modules: JavaScript Scoping of ShadowDom Children (Issue #959)

`host` in scope can be polyfilled like this:

````diff
+ <template id="hostScopeTemplate">
+   <div>
+     <script>var host = null</script>
+     <button hidden onclick="host = this.getRootNode().host" />
+   </div>
+ </template>
<template id="myCustomElementTemplate">
  <button onclick="host.handleClick()"><slot></slot></button>
</template>

<script type="module">
+  let scopeTemplate;

+  function setHostInScope(shadowRoot) {
+    scopeTemplate = scopeTemplate ?? document.getElementById('hostScopeTemplate');
+    shadowRoot.appendChild(scopeTemplate.content.cloneNode(true));
+    shadowRoot.querySelector('button').click()
+    shadowRoot.querySelector('div').remove();
+  }

  /* ... */
  class myCustomElement extends HTMLElement {
    static {
      customElements.define('x-button', this);
    }
    constructor() {
      super();
      const shadowRoot = this.attachShadow({ mode: "open" });
      setHostInScope(shadowRoot);
+      const template = document.getElementById("myCustomElementTemplate");
      shadowRoot.appendChild(template.content.cloneNode(true));
    }
    handleClick() {
      window.alert('You clicked me!');
    }
  }
  /* ... */
</script>

<x-button>Click me</x-button>
````

Hacky, but it works. It's probably cleaner to have `myCustomElement` extend something other than `HTMLElement` for multiple components. There's no access to private fields though.

The click workaround is because scripts can't know it's element/context. If it wasn't for that, we could eliminate the hidden click and it would be one liner that doesn't need to be removed.


-- 
Reply to this email directly or view it on GitHub:
https://github.com/WICG/webcomponents/issues/959#issuecomment-1378959609
You are receiving this because you are subscribed to this thread.

Message ID: <WICG/webcomponents/issues/959/1378959609@github.com>

Received on Wednesday, 11 January 2023 15:33:38 UTC