Skip to content

Get self instance from inside of a component #14163

@Freeskier

Description

@Freeskier

Describe the problem

In my project I needed a self instance of the component itself. What I mean by that I will provide in an example below.
From the docs:
App.svelte

<ShoppingCart bind:this={cart} />

<button onclick={() => cart.empty()}> Empty shopping cart </button>

ShoppingCart.svelte

<script>
	// All instance exports are available on the instance object
	export function empty() {
		// ...
	}
</script>

This is a valid code and you can store the reference of ShoppingCart in the parent component.

In my scenario, I needed to pass the same cart reference, but from inside of the ShoppingCart.
Of course there is a workaround by storing and passing the reference as a props to the child component like below:
App.svelte

<ShoppingCart bind:this={cart}  ref={cart}/>

ShoppingCart.svelte

<script>
	let { ref } = $props()
       *** now I have access to ref***
	export function empty() {
		// ...
	}
</script>

Describe the proposed solution

I'm not that deep into the fundametals of the svelte, thats why I don't know if my proposition has any sense.
But what about consider $self() rune?

Importance

would make my life easier

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