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.
- Host: GitHub
- URL: https://github.com/astef/model-events
- Owner: astef
- License: mit
- Created: 2022-08-14T16:49:11.000Z (almost 4 years ago)
- Default Branch: main
- Last Pushed: 2022-08-27T23:20:43.000Z (almost 4 years ago)
- Last Synced: 2025-06-17T16:55:37.236Z (about 1 year ago)
- Language: TypeScript
- Size: 65.4 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# model-events
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);
```