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

This may require its own champion and proposal/explainer, but I feel like it falls well enough in line that it might be worth mentioning: Scoping of JavaScript references inside of `<template>`, potentially to their accompanying inline `<script type="module">` tags. This would alleviate under-utilization of inline JavaScript as it is right now. Being able to use `on*=` attributes, and others, while referencing the included class would be incredibly useful.

To elaborate slightly (before rushing to dinner), the actual mechanism may include waiting to evaluate JS references in attributes for children of a `template` tag until the ShadowDom is registered. Even if all we do is set the context (`this`) to the currently relevant instance, that would be a huge win for Web Components.

```javascript
<template id="myCustomElementTemplate">
    <button onclick="this.#handleClick">Click me!</button>
</template>

<script type="module">
    /* ... */
    class myCustomElement extends HTMLElement {
        constructor() {
            super();
            // ShadowDOM is attached to instance of myCustomElement here
            let shadowRoot = this.attachShadow({ mode: "open" });
            let template = importDoc.getElementById("myCustomElementTemplate");
            // The `this` of any children of a ShadowRoot will be equal to the instance of the
            // element, allowing access to public **and private** methods
            shadowRoot.appendChild(template.content.cloneNode(true));
        }
        #handleClick(e) {
            console.log("Clicked!", e);
        }
    }
    /* ... */
</script>
```

Again, this may very well need to be in its own proposal.

This could potentially pave the way for other mechanisms, including (one which is certainly out of the scope of this proposal): binding attribute values to instance properties, and so on.

_Originally posted by @Swivelgames in https://github.com/WICG/webcomponents/issues/645#issuecomment-1114372075_

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

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

Received on Monday, 2 May 2022 21:03:23 UTC