Search code examples
javascriptsveltesvelte-3svelte-store

Svelte: How to subscribe to store inside a class instance


How do I subscribe to a writable() instance of a class?

class User{
    public money: Writable<number> = writable(0);

    public goToJob(){
        money.update(prev => prev + 100);
    }
}

<script>
    let user = new User();
</script>

<div>{user.$money}</div>
<button on:click={() => user.goToJob()}>Go to Job</button>

When I click on the button, I expect the money to be added and reflected on the div. It doesn't update however, though I'm correctly referencing the money store.


Solution

  • Solved; Quite easy actually. Just de-structure the class instance:

    <script>
        let user = new User();
        let { money } = user;
    </script>
    
    <div>{$money}</div>
    <button on:click={() => user.goToJob()}>Go to Job</button>