Skip to content

Get a reference to the "root" element when creating a "custom element" #3593

Closed
@petterek

Description

@petterek

When trying to create a CustomEvent in a custom element I want the dispatcher of the event to be the custom element. (I have tried to use the createEventDispatcher, but that did not work).

E.G

<script>
var el = document.getElementById("el1");
el.addEventListener("customEvent",(e)={});

</script>


<my-custom-svelte-element id=el1></my-custom-svelte-element>

To be able to do this right now, you have to get a reference to the current my-custom-svelte-element inside your code.
What i have seen is that in the compiled code function instance($$self, $$props, $$invalidate) is the function that is called when initializing the component. And the $$self is actually the right element.. But trying to access it pre compile gives me an error about $$self is not an legal param name..
Trying to access just self actually gives me window 😄 but that I think, is an undocumented feature...

To achieve what I need at this moment, a new function similar to the createEventDispatcher named something like createElementEventDispatcher witch compiles down to something like createElementEventDispatcher($$self) and inside this captures the $$self and exposes a dispatch method that matches the

element.dispatchEvent(
    new CustomEvent(
                         'eventName',
                         {
                             detail: {value:4}, //This is your custom event data.. 
                             composed: true, //Needed to get out of the shadowRoot scope
                             bubbles: true
                          }
                     )
               )

this would make it easy to raise events from inside your custom element and to the DOM.

This would be a very 'narrow' solution to my problem and a more generic one would be to be able to get the reference to the $$self parameter.. then it would be possible to dispatch the event your self. Maybe a special directive of some kind..

I think this is a really basic functionality when creating custom-elements, at least in my case where the custom elements are more like self contained widgets that needs to communicate through events and attributes.

And also very basic thing when it comes to micro front ends.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions