An event is a message the engine sends when something happens: the engine finished starting, a statement ran, a save loaded. Your game can listen for any of them with monogatari.on() and run code of its own when it arrives: count the lines a player has read, change something on the screen after a load, send a number to your analytics.

Events are standard browser CustomEvents, fired on the game’s <visual-novel> element. The data an event carries is in its detail property. An event whose name starts with will fires before something happens, and one that starts with did fires after it.

Listen to an event

Add listeners in js/main.js, inside $_ready(…) and before monogatari.init(…):

// js/main.js
$_ready(() => {
  monogatari.on('didLoadGame', () => {
    console.log('A save was loaded');
  });

  monogatari.init('#monogatari').then(() => {
    // …
  });
});

Load a save, and the browser console prints A save was loaded.

The listener gets the event. Read what it carries from event.detail:

monogatari.on('didRunAction', (event) => {
  console.log('Ran:', event.detail.action.constructor.id);
});

Each statement the game runs prints its action, like Ran: Dialog or Ran: Scene.

In a listener written with function, this is the <visual-novel> element, not the engine: use monogatari to reach the engine.

Why inside $_ready

The browser runs your files before it has read the page’s <body>, where <visual-novel> is. monogatari.on() attaches the listener to that element, so it needs the element to exist:

  • At the top of a file (outside $_ready), the element isn’t there yet. The listener is never added, and with the debug module an error dialog opens, titled Main element is not ready yet.
  • Inside $_ready, before init(), the element exists and the engine hasn’t started: the listener hears every event from willInit on.
  • After init() resolved, the start-up events have already fired.

An error dialog titled "Main element is not ready yet", whose message reads "Monogatari attempted to execute a function when the main element was not fully loaded yet."
What a listener added at the top of js/main.js opens. Its help section shows where to move the code.

Calls at the top of your files that change the state or the configuration (state({ … }), configuration('credits', { … })) fire their events too, before the element exists. Those events are fired on window once the page has loaded, so monogatari.on() listeners don’t hear them.

on()

Adds a listener.

on(event: string, callback: (event: Event) => void): void
on(event: string, selector: string, callback: (event: Event) => void): void
Parameter Type What it is
event string The event’s name: an engine event from this page, one of your own, or a browser event such as 'click'. Several names separated by spaces add the listener to each.
selector string Optional. A CSS selector: the listener then runs only for events that come from an element inside <visual-novel> matching it (or from inside such an element), including elements added later.
callback function What runs. It gets the event.

Returns nothing. With a selector, this in the callback is the matching element. This counts the player’s picks in choices:

let picks = 0;

monogatari.on('click', '[data-choice]', function() {
  picks += 1;
  console.log(`Picked "${this.dataset.choice}", ${picks} picks so far`);
});

off()

Removes a listener added with on().

off(event: string, callback: (event: Event) => void): void

Pass the same event name and the same function, so keep the function in a constant. It removes listeners added with a selector too.

const onLoad = () => {
  console.log('A save was loaded');
};

monogatari.on('didLoadGame', onLoad);

// Later, when you no longer want it:
monogatari.off('didLoadGame', onLoad);

trigger()

Fires an event on <visual-novel>.

trigger(name: string, detail?: object): void
Parameter Type What it is
name string The event’s name.
detail object Optional. What listeners find in event.detail. An empty object when you leave it out.

The event doesn’t bubble: the listeners on <visual-novel>, where on() puts them, hear it. If the element isn’t in the page yet, the event is fired on window once the page has loaded.

Use it for events of your own. You can fire the engine’s events with it, but listeners then act as if the engine had done what the event reports.

The order of events

These are the events of a few common moments, in the order the engine fired them in a test game (Chromium and Firefox give the same order). willUpdateState, didUpdateState, componentDidMount and componentDidUnmount fire many times in between, and the configuration events a few times while the engine starts; they are left out.

Opening the game, served:

willInit > willSetup > didSetup > willBind > didBind > willLocalize > didLocalize > didInit
> willPreloadAssets > assetQueued (one per file) > assetLoaded or assetFailed (one per file) > didPreloadAssets

The main menu appears after didPreloadAssets. Opened from a file, the preloading doesn’t run, and the list ends at didInit.

A line of dialog (y Hello.), from the click that reaches it:

willRunAction > didStartTyping > didRunAction > didStartTyping > didFinishTyping

didFinishTyping fires once the whole line is on the screen.

A choice appearing, with its question ('Dialog': 'y Pick one.'):

willRunAction (Choice) > didStartTyping > didStartTyping > didRunAction (Choice) > didFinishTyping

A click on a choice that jumps to another label:

willRunAction (Jump) > willRunAction (Dialog) > didRunAction (Jump) > didStartTyping > didRunAction (Dialog) > didStartTyping > didFinishTyping

Going back from the first line of that label to the choice:

willRevertAction (Choice) > willRevertAction (Jump) > didRevertAction (Jump) > didStartTyping > didStartTyping > didRevertAction (Choice) > didFinishTyping

Loading a save from the load screen:

willLoadGame > didLoadGame > willRunAction > didStartTyping > didRunAction > didStartTyping > didFinishTyping

The statement the player saved on runs after didLoadGame.

Every event

Starting the engine

init() fires these, in this order, each once.

Event Detail When it fires
willInit init() starts.
willSetup Before setup(): the player’s preferences haven’t been read yet.
didSetup setup() finished: the components are defined, the preferences read, each action’s and component’s setup() done.
willBind Before bind().
didBind bind() finished: the buttons and keys work.
didInit The engine is set up. The first screen isn’t showing yet: the preloading and the main menu (or the language selection screen) come after it.

Preloading assets

preload() fires these while the loading screen shows. They don’t fire when the Preload setting is false, in the desktop app, or in a game opened from a file.

Event Detail When it fires
willPreloadAssets The preloading starts.
assetQueued { name, type, category } A file is added to the list, once per file. Without a default preload block, a file declared twice (a sprite that is also an expression) is queued once.
assetLoaded { name, type, category } A file finished loading. Without a default block, name is the file name ('hall.png') and type is 'image' or 'file'; with one, name is the asset’s name and type is 'image' or 'audio'. category is 'scenes', 'music', 'characters' and so on.
assetFailed { name, type, category, url, error } A file couldn’t be loaded: url is the address that was asked for and error what the browser reported. Each queued file ends with either assetLoaded or assetFailed.
didPreloadAssets Every file has finished, loaded or failed.

Before 2.9.0, assetQueued fired once per character instead of once per picture, assetFailed didn’t exist, and one file that failed kept didPreloadAssets from firing.

Statements

Event Detail When it fires
willRunAction { action } The engine found the action for a statement and is about to run it.
didRunAction { action } The action has run, before the game goes on to a next statement. A line of dialog may still be typing.
willRevertAction { action } A statement is about to be undone, as the player goes back.
didRevertAction { action } The statement was undone.

action is the action object that runs the statement. action.constructor.id is the action’s name ('Dialog', 'Scene', 'Show::Character', 'Jump'), and action._statement the statement as the script wrote it.

A function in the script fires neither willRunAction nor didRunAction.

let linesSeen = 0;

monogatari.on('didRunAction', (event) => {
  if (event.detail.action.constructor.id === 'Dialog') {
    linesSeen += 1;
  }
});

Typing

The type writer fires these as a line of dialog appears.

Event Detail When it fires
didStartTyping A line starts typing. It fires once for each typed line. Before 2.9.0 it fired twice.
didFinishTyping The whole line is on the screen: it finished typing, the player clicked to finish it, or it was shown at once.

A line shown at once, without typing (the TypeAnimation setting off, or a character whose type_animation is false), fires only didFinishTyping.

The state

Event Detail When it fires
willUpdateState { oldState, newState } state() is about to change the state. oldState is a copy of the state before; newState the state it’s about to become.
didUpdateState { oldState, newState } The state changed. newState is the state now.

Every change fires them, the engine’s own included: several times for each statement (step changes, a scene is shown, a song starts).

monogatari.on('didUpdateState', (event) => {
  const { oldState, newState } = event.detail;

  if (newState.label !== oldState.label) {
    console.log(`Now in label ${newState.label}`);
  }
});

Loading a save

Event Detail When it fires
willLoadGame loadFromSlot() read the save and is about to load it: the player picked a slot, or your code called it. The game hasn’t been reset yet. A slot that can’t be loaded (no save, or its label is gone) fires nothing.
didLoadGame The save is loaded: the state and the storage are back, the scene, characters and music are rebuilt, and the game screen shows. The statement the player saved on hasn’t run yet.

Saving fires no event.

Configuration

configuration() fires these.

Event Detail When it fires
configurationElementWillUpdate configuration(key, object) is about to change a part.
configurationElementUpdate::<key> { newConfiguration, oldConfiguration } The same moment, with the part’s key in the name: configurationElementUpdate::credits. newConfiguration is the object given, oldConfiguration the part as it was.
configurationElementDidUpdate The part changed.
configurationWillUpdate, configurationDidUpdate Before and after configuration(object) changes its parts. Each part fires the three events above in between.

The quick menu sets its own buttons as the game starts, so configurationElementUpdate::quick-menu fires during init().

Interface strings

Event Detail When it fires
willLocalize localize() starts: during init(), when the player picks a language, and when your code calls it.
didLocalize The page shows the strings of the player’s language.

Components

Event Detail When it fires
componentDidMount { component, tag } A component’s element was added to the page and drawn. component is the element, tag its tag name.
componentDidUnmount { component, tag } A component’s element left the page.

They fire for every component element, often: the text box and its type writer leave the page and come back with each line.

Events of your own

Fire an event of your own with trigger() and listen to it with on(). Pick a name the engine doesn’t use:

$_ready(() => {
  monogatari.on('chapterStarted', (event) => {
    console.log(`Chapter ${event.detail.chapter} begins`);
  });

  monogatari.init('#monogatari');
});

monogatari.script({
  'Chapter2': [
    function() {
      this.trigger('chapterStarted', { chapter: 2 });
    },
    'y A new day.',
    'end',
  ],
});

When the game reaches Chapter2, the console prints Chapter 2 begins.