1.0.0-alpha.7 • Published 2 years ago

model-events v1.0.0-alpha.7

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

model-events

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

Installation

npm install model-events

Example

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<typeof modelSchema>;

// 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);