Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/xelaok/svelte-mobx

Reactive MVVM with MobX & Svelte
https://github.com/xelaok/svelte-mobx

mobx mvvm reactive state-management svelte

Last synced: 2 months ago
JSON representation

Reactive MVVM with MobX & Svelte

Awesome Lists containing this project

README

        

## svelte-mobx ([npm](https://www.npmjs.com/package/svelte-mobx))
[MobX](https://mobx.js.org) connector for [Svelte](https://svelte.dev)

## Installation

```bash
npm i svelte-mobx
```

## Usage ([example repository](https://github.com/xelaok/svelte-mobx-example))

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

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

```svelte
// App.svelte

import { connect } from "svelte-mobx";

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

let currentTimeString;
let elapsedSecondsString;

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


The time is {currentTimeString}


This page has been open for {elapsedSecondsString}


```

```typescript
// 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();
}
}
```