Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference to "this" component in Svelte

From what I've read this seems like currently it's not possible: https://github.com/sveltejs/svelte/pull/4523#issuecomment-596232030

I want to build a tree structure, and want to highlight an active node anywhere on the tree. If I use a store to write/read the currently active node ID, it's pretty easy, just check if the ID matches the component's.

But if I have thousands of nodes, I'm afraid this might get pretty slow as each node checks when current ID changes.

So I thought I could instead store a reference to the currently active node so I could deactivate/activate any node easily. For example:

import { activeNode } from './stores'

let active = false

export function activate() {
  $activeNode.deactivate()
  activeNode.set(this) // <- this is undefined
  active = true
}

export function deactivate() {
  active = false
}

I believe something like this would be much faster, as I could call the activate method as necessary on any node.

So how can I reference a component instance? Or is there a better approach?

like image 573
Ivan Avatar asked Feb 14 '26 22:02

Ivan


1 Answers

You can very hackishly access this with an eval (don't do it), or quite hackishly with complicity of the parent component (bind:this)... But you don't need to.

What about exposing just what is needed by the external world?

<script>
    import { activeNode } from './stores.js'

    let active = false

    const api = {
        activate() {
            if ($activeNode) $activeNode.deactivate()
            $activeNode = api // sugar for: activeNode.set(api)
            active = true
        },
        deactivate() {
            active = false
        }
    }
</script>

<div class:active>
    Node
</div>

<style>
    .active {
        font-weight: bold;
    }
</style>
like image 200
rixo Avatar answered Feb 21 '26 16:02

rixo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!