Search code examples
javascriptsveltesvelte-3svelte-component

How to listen to a svelte event in a HTML page?


I have a simple Svelte button component as follows.

<script lang="ts">

  import { createEventDispatcher } from 'svelte';
  import { idGenerator } from '../utils/helpers';

  export let id = idGenerator();
  export let label = 'Click';
  export let styleClass: string = '';

  const dispatch = createEventDispatcher();

  const calculatedClasses = '...'

  const buttonClicked = $event => {
    console.log('TARGET', $event); // This console is outputting the click event.
    dispatch('message', {text: 'Hello'});
  }
</script>

<button on:click={buttonClicked} class={calculatedClasses()} id={id}>
  {label}
</button>

<svelte:options tag="aurora-button"></svelte:options>

The main.ts is as follows:

export * from './lib/Button.svelte'

I want to listen to the clicked event of the button in the index.html file, which is as follows:

<body>
   <script type="module" src="/src/main.ts"></script>
   <aurora-button size="large" type="success" on:message="clicked()"></aurora-button>
   <script>
      function clicked($ev) {
          console.log('EV', $ev);
     }
   </script>
</body>

I'm not able to listen to the event sent from Svelte component in the html file. Am I not doing it right? The answers I've been seeing online are the one's which are using Svelte component using inside another Svelte component.

In the browser, I'm getting <aurora-button> was created with unknown prop 'on:message'.


Solution

  • You cannot use Svelte syntax in plain HTML.

    on:... is just syntactic sugar for addEventListener. So you could do something like:

    <script type="module">
      document.querySelector('aurora-button')
        .addEventListener('message', e => console.log(e));
    </script>
    

    (I am not entirely sure about the initialization timeline for custom elements generated by Svelte, it might be important that the element is registered before adding the event listener, hence the type="module" to make it run after the component code.)