svelte-mobx Svelte Themes

Svelte Mobx

Reactive MVVM with MobX & Svelte

svelte-mobx (npm)

MobX connector for Svelte

Installation

npm i svelte-mobx

Usage (example repository)

import App from "./App.svelte";
import { AppVm } from "./App.vm";

new App({
    props: { vm: new AppVm() },
    target: document.body,
});
// App.svelte

<script context="module">
    import { connect } from "svelte-mobx";
</script>

<script>
    export let vm;
    const { autorun } = connect();

    let currentTimeString;
    let elapsedSecondsString;

    $: autorun(() => {
        currentTimeString = vm.currentTimeString;
        elapsedSecondsString = vm.elapsedSecondsString;
    });
</script>

<div>
    <h1>The time is {currentTimeString}</h1>
    <div>This page has been open for {elapsedSecondsString}</div>
</div>
// App.vm.ts

export class AppVm {
    startTime = new Date();
    currentTime = new Date();

    constructor() {
        makeAutoObservable(this, {
            startTime: observable,
            currentTime: observable,
            elapsedSeconds: computed,
            currentTimeString: computed,
            elapsedSecondsString: computed,
            updateCurrentTime: action,
        });

        setInterval(() => this.updateCurrentTime(), UPDATE_INTERVAL);
    }

    get elapsedSeconds() {
        return Math.round((this.currentTime.getTime() - this.startTime.getTime()) / 1000);
    }

    get currentTimeString() {
        return timeFormatter.format(this.currentTime);
    }

    get elapsedSecondsString() {
        return `${this.elapsedSeconds} ${this.elapsedSeconds === 1 ? "second" : "seconds"}`;
    }

    updateCurrentTime() {
        this.currentTime = new Date();
    }
}

Top categories

Loading Svelte Themes