crisward / svelte-tag

MIT License
52 stars 8 forks source link

Dispatch custom event #5

Closed nldn closed 1 year ago

nldn commented 3 years ago

How can we dispatch a custom event that can be caught in the host application?

<html>
    <body>
        <my-component></my-cmponent>
    </body>

    <script>
        document
            .querySelector("my-component")
            .addEventListener("customEvent", (e) => console.log(e.detail));
    </script>
</html>
crisward commented 3 years ago

Pretty sure events only bubble up if the composed flag is set.


<script>

  const event = new CustomEvent('customEvent', {
    detail: 'Hello parent!',
    bubbles: true,
    cancelable: true,
    composed: true // makes the event jump shadow DOM boundary
  });

  function sayHello(e){
    e.target.dispatchEvent(event);
  }

</script>
<div>
   <button on:click={sayHello}>Say Hello</button>
</div>

Fairly sure the default event dispatcher in svelte doesn't do that. The above is a browser api.

https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent