Vasta Logo
Models

Events

Defining lifecycle events for models with Vasta.

Lifecycle events let you run custom logic before and after model persistence.

Define them in the events object passed to defineModel:

import { defineModel } from "vasta-orm";
import db from "@/database/db";

export default class Pet extends defineModel({
  db,
  table: "pets",
  events: {
    created: async (pet) => {
      console.log(`Created pet ${pet.attributes.name}`);
      await someAsyncFunction();
    },
    deleting: (pet) => {
      console.log(`Deleting pet ${pet.attributes.id}`);
    },
  },
}) {}

Event handlers receive the model instance as a parameter and should not return anything. They may be async functions, and Vasta will wait for them to resolve before proceeding.

Supported events:

  • creating
  • created
  • updating
  • updated
  • saving
  • saved
  • deleting
  • deleted

Dispatch behavior:

  • New model save() dispatches: savingcreatingcreatedsaved
  • Existing dirty model save() dispatches: savingupdatingupdatedsaved
  • Existing clean model save() dispatches: savingsaved
  • delete() dispatches: deletingdeleted

Events ending with -ing run before persistence. Events ending with -ed run after persistence.

Copyright © 2026