Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create custom directives in svelte?

Tags:

svelte

I know there are slots and some discussion about slots without DOM elements. What about custom directives? (That is, special "atributes" that will modify the behavior of a component/DOM element)

like image 905
Bernardo Dal Corno Avatar asked Mar 03 '23 22:03

Bernardo Dal Corno


2 Answers

There are no custom directives just yet like you might find in Vue, but you can certainly bind actions to child elements with use:something. See the docs here. You can also find an official example here.

Here's a small example:

<button on:click={doSomething} use:tooltip={calculatedTooltip}>
    Click Me
</button>
like image 167
parker_codes Avatar answered Mar 15 '23 03:03

parker_codes


Coming from an Angular background, I wondered the same. I was happy to see there's something similar in Svelte thanks to GoogleMac's answer.

If you are used to Angular, you'd probably be looking for event dispatches too (@Output in Angular). It seems like there's not such a concept in Svelte's actions but you can make use of parameters. Here's an example:

// outside-click.js => Action
export function outsideClick(node, onOutsideClick) {
  //                               ^^^^^^^^^^^^^^ parameter
  function handleClick ({ target }) {
    const clickedOutside = !node.contains(target);

    if (clickedOutside) {
      onOutsideClick();
    }
  }

  window.addEventListener('click', handleClick);

  return {
    destroy () {
      window.removeEventListener('click', handleClick);
    }
  };
}
// MyComponent.svelte => component
<script>
  function hideMenu() {
    // hide menu logic
  }
</script>

<div use:outsideClick={hideMenu} class="menu">
  <!-- Menu that has to be closed when clicking outside of it -->
</div>

Hope this would help someone.

like image 25
Yulian Avatar answered Mar 15 '23 04:03

Yulian