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

https://github.com/astef/model-events

Receive events from your model field changes.
https://github.com/astef/model-events

Last synced: 12 months ago
JSON representation

Receive events from your model field changes.

Awesome Lists containing this project

README

          

# model-events

NPM version

TypeScript-first zero-dependency package to generate events from your model field changes.

## Installation

`npm install model-events`

## Example

```typescript
import { defineModel, defineObject, defineField, Infer } from "model-events";

// define your schema just as you define types
const modelSchema = defineModel(
{
player1: defineObject({
score: defineField(0),
}),
player2: defineObject({
score: defineField(0),
}),
},
{
name: defineField("Round 1"),
}
);

// and infer your actual type later
type TwoPlayerGameModel = Infer;

// create an instance with default field values
const model: TwoPlayerGameModel = modelSchema.create();

// subscribe to field updates
model.on("value", (field, value) => {
// field index is unique within the entire model
console.log(`[${field.index}]=${value}`);
});

// and finally do your computations!
function play(model: TwoPlayerGameModel) {
for (let i = 1; i <= 10; i++) {
model.player1.score += 33 % i;
model.player2.score += model.player1.score % 5;
}
}

play(model);
```