Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton in Svelte

Tags:

svelte

I am trying to make a Svelte app, where I have a class (not svelte component) that create an audioSource, and manage it.

I would like to get this class instance across multiple component.

Right now, the only way I found is to do this :

<script lang="ts" context="module">
  import { AudioAnalyser } from "@app/class/audio/AudioAnalyser";
  import type { MediaAnalyser } from "@app/types/analyser";

    let analyser: MediaAnalyser = new AudioAnalyser();
</script>

Inside a component, so I am sure there is only one instance, and share that instance via property binding with other Component.

But I am trying to find a way where I could instantiate this class once and access it trought all the app like with an angular Service.

thank you

like image 201
Crocsx Avatar asked May 13 '26 15:05

Crocsx


2 Answers

Instead of instantiating this in a svelte component, you can do so in a regular script file:

// analyser.ts
import { AudioAnalyser } from "@app/class/audio/AudioAnalyser";
import type { MediaAnalyser } from "@app/types/analyser";

const analyser: MediaAnalyser = new AudioAnalyser();

export default analyser

Now you simple import this wherever you need:

<script>
  import analyser from './analyser.ts'
</script>

The instantiation will only happen once.

like image 82
Stephane Vanraes Avatar answered May 15 '26 09:05

Stephane Vanraes


In my application, I use a Singleton inside a typescript file. This singleton can then store unique data that will be shared across my application from any other .svelte component.

You can create a typescript Singleton like so :

export class EditorConfig {
    private static instance : EditorConfig;
    private constructor(){}
    public static getInstance(): EditorConfig {
        if(!EditorConfig.instance){
            EditorConfig.instance = new EditorConfig();
        }
        return EditorConfig.instance;
    }

    public myvariable = "";

    public helloworld(){
       EditorConfig.getInstance().myvariable = "hello world";
       console.log(EditorConfig.getInstance().myvariable)
    }

You can than import this typescript file inside a svelte component like this :

<script>
   import {EditorConfig} from './EditorConfig.ts'

   EditorConfig.getInstance().helloworld()
</script>

But you can also do this with svelte store. You can find some examples in the svelte officiel documentation.

like image 38
Tryall Avatar answered May 15 '26 09:05

Tryall



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!