Skip to content

Implement <svelte:target> special component. #1321

@hperrin

Description

@hperrin

Having a <svelte:target> special component that references the component's target element would be really useful instead of having to use addEventListener on this.options.target.

Basically, turn this:

{#if show}
  <span class="tooltip">{text}</span>
{/if}

<script>
  export default {
    oncreate() {
      this.set({'mouseover': () => { this.set({'show': true}); }});
      this.set({'mouseout': () => { this.set({'show': false}); }});
      this.options.target.addEventListener('mouseover', this.get('mouseover'));
      this.options.target.addEventListener('mouseout', this.get('mouseout'));
    },
    ondestroy() {
      this.options.target.removeEventListener('mouseover', this.get('mouseover'));
      this.options.target.removeEventListener('mouseout', this.get('mouseout'));
    },
  };
</script>

Into this:

<svelte:target on:mouseover="set({'show': true})" on:mouseout="set({'show': false})">
  {#if show}
    <span class="tooltip">{text}</span>
  {/if}
</svelte:target>

Or maybe this:

<svelte:target on:mouseover="set({'show': true})" on:mouseout="set({'show': false})" />
{#if show}
  <span class="tooltip">{text}</span>
{/if}

And make it a lot easier to do things like this:

<svelte:target href="/app/{ section }/{ entity }" />
const link = new Link({
  target: domAnchorElement,
  data: {
    section: domAnchorElement.dataset.section,
    entity: domAnchorElement.dataset.entity
  }
});

Edit: Updated for v2.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions