Action Life Cycle
An action has two kinds of methods, and the difference matters for everything on this page:
- Static methods (
static async setup()) belong to the action’s class. The engine calls them once, or on every registered action at the same moment: setting up, asking whether the game may move on, starting a game, loading a save. - Instance methods (
async apply()) belong to the object the engine creates for one statement. They run that statement, or undo it.
Inside both, this.engine is the engine.
The whole cycle
Undoing statements has a page of its own: Going Back and Saving.
Mounting
Mounting runs once, when monogatari.init() runs, for every registered component and action. It has three phases, and each one finishes for every component and action before the next starts. Within a phase, the engine calls them all at once and waits for all of them, so don’t count on another action’s setup() having finished inside yours; wait for bind() or init().
An action registered after monogatari.init() started doesn’t get these phases.
static async setup()
Prepare what the action needs: give its keys in the game’s state a starting value, and create the histories it keeps.
static async setup() {
this.engine.state({ location: '' });
this.engine.history('location');
}setup() receives the selector monogatari.init() was given, like bind() and init(): '#monogatari' in the starter game. Before 2.9.0 it received nothing.
static async bind(selector)
Attach listeners. selector is what monogatari.init() was given: '#monogatari' in the starter game.
| Call | What it listens to |
|---|---|
this.engine.registerListener('name', { callback }) |
Clicks on any element with data-action="name". Add keys: 'shift+f' to run it from the keyboard too. See Waiting for the player. |
this.engine.keyboardShortcut('shift+f', callback) |
A key or a combination of keys. |
this.engine.on('click', '.my-class', callback) |
An event on the game’s <visual-novel> element, from any element inside it that matches the selector. |
static async init(selector)
Anything that needs every component and action to be set up and bound first.
Applying a statement
These three run in order for the one statement the instance was created for. Each can be asynchronous; the engine waits for one before calling the next.
async willApply()
Checks before anything happens. Throwing, or returning a rejected promise, stops the statement: it isn’t applied. See When a method throws before you rely on it.
async apply()
The statement’s work: create elements, play media, change the state.
async didApply()
Decide what happens next, and return it:
{ advance: true }: run the next statement right away, asshow sceneandplay musicdo.{ advance: false }: stop and wait for the player, as dialog does. This is what the base class returns, so an action that waits can leavedidApply()out.
async didApply() {
return { advance: true };
}The engine calls didApply() without an argument. Several built-in actions accept { updateHistory, updateState } and run their own statements again with both set to false, to show them without recording them twice; Going Back and Saving uses the same idea.
When a method throws
When the constructor, willApply(), apply() or didApply() throws or rejects, the statement stops where it is:
- The debug module shows an error dialog. When your action showed none of its own while the statement ran, the dialog is A statement failed, with your action’s id, the method that failed and your error’s message.
- The line on screen before the statement stays there. Once the dialog is closed, the next click goes on with the statement after the failed one, and Back works: going back steps over the statement that failed, without calling its
revert(). - The console shows the error, and with
monogatari.debug.level(5)also “Will Apply Failed” or “Apply Failed”.
So throw only when the statement really can’t go on, and report the problem first, so whoever wrote the script sees what to fix. When you can, show the error and carry on with a sensible default instead.
A didApply() that returns nothing counts as { advance: false }: the game waits for the player, and the console warns that it should return { advance }.
Moving the game forward
static async shouldProceed({ userInitiated, skip, autoPlay })
Every way the game moves on from a statement that waits asks this of every registered action and component. Throw or reject to refuse. The argument says what is moving the game:
| Property | true when |
|---|---|
userInitiated |
The player clicked the game screen, or pressed Space or the Right Arrow key. |
skip |
Skip mode is moving the game. |
autoPlay |
Auto-play is moving the game. |
Before it asks the actions and components, the engine refuses by itself while an element with the modal class is visible (a confirmation, the error dialog), while the text box is hidden with Hide, and while a statement is still running.
shouldProceed() guards each attempt to move on. It isn’t asked between statements that return { advance: true } and run one after another.
static async willProceed()
Called on every action and component once no one refused, right before the next statement runs. Take down what should disappear when the player moves on. Don’t throw here: a rejection cancels the move and opens an error dialog. Refuse in shouldProceed() instead.
Waiting for the player
Some actions wait for something other than a click on the game screen: a choice, a text field, a button of your own. A click anywhere must not move past them. The built-in Choice, Input and Message actions all do it the same way, and so can yours:
- A
static blockingflag that’struewhile the action waits. - A
shouldProceed()that refuses while the flag istrue. - A listener that clears the flag and moves the game on when the player is done.
- A
willRollback()and areset()that clear the flag, so going back, quitting or loading never leaves the game refusing every click.
This action shows a Continue button, and the game only moves on when the player presses it. Add it to js/main.js:
class ContinueButton extends Monogatari.Action {
static id = 'ContinueButton';
// True while the button is on screen and the game waits for it.
static blocking = false;
static async bind() {
// Runs when an element with data-action="continue-button" is clicked.
this.engine.registerListener('continue-button', {
callback: () => {
ContinueButton.remove();
this.engine.proceed({ userInitiated: true, skip: false, autoPlay: false }).catch((reason) => {
this.engine.debug.log('Proceed prevented', reason);
});
},
});
}
// Asked before the game moves on: refuse while the button is waiting.
static async shouldProceed() {
if (ContinueButton.blocking) {
throw new Error('The Continue button has not been pressed.');
}
}
// The player goes back while the button is on screen.
static async willRollback() {
ContinueButton.remove();
}
// A game ends, or a save is about to load.
static async reset() {
ContinueButton.remove();
}
static remove() {
ContinueButton.blocking = false;
this.engine.element().find('.continue-button').remove();
}
static matchString([keyword]) {
return keyword === 'continue-button';
}
async apply() {
const button = document.createElement('button');
button.className = 'continue-button';
button.dataset.action = 'continue-button';
button.textContent = 'Continue';
this.engine.element().find('[data-screen="game"]').append(button);
ContinueButton.blocking = true;
}
async didApply() {
return { advance: false };
}
// The player went back to this statement: show the button again.
async revert() {
await this.apply();
}
async didRevert() {
return { advance: false, step: true };
}
}
monogatari.registerAction(ContinueButton);Give the button a place on screen in style/main.css:
.continue-button {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 11;
}And use it in js/script.js:
monogatari.script({
'Start': [
'show scene afternoon',
'The letter is sealed.',
'continue-button',
'You break the seal.',
'end',
],
});After “The letter is sealed.”, the button appears in the middle of the screen. Clicking anywhere else, or pressing Space, does nothing; pressing Continue shows “You break the seal.”. Press Back from there and the button comes back, with “You break the seal.” still in the text box, since no line of dialog was shown again. Press Back once more and “The letter is sealed.” shows.

What each part does:
- The listener.
data-action="continue-button"makes the engine’s click handler run the listener namedcontinue-button, and stops the click there, so it doesn’t also reach the game screen.this.engine.proceed()then moves the game on as a click would, askingshouldProceed()first; the flag is already cleared, so it passes. willRollback()runs when the player presses Back while the button is waiting. It takes the button away, and the engine goes back to the line before it.revert()anddidRevert()run when the player goes back to this statement from the line after it.revert()shows the button again;{ advance: false, step: true }makes the game stop there and wait. Going Back and Saving explains the two values.reset()runs when the player quits, and before a save loads. A save made while the button was waiting points at this statement, so after the load the engine runs it again and the button comes back.
WARNING
Don't wait for the player inside apply() or didApply(). Return, and continue from the player’s event, as the listener above does and as the built-in Message, Choice and Input actions do.
Going back
static async shouldRollback() and static async willRollback() work like their forward counterparts. They’re asked of every action and component when the player presses Back in the quick menu or the Left Arrow key, which only works while the AllowRollback setting is true. Throw or reject in shouldRollback() to refuse. The engine refuses by itself while the text box is hidden with Hide and while a statement is still running.
Then the engine undoes the statements before the current one with each one’s willRevert(), revert() and didRevert(). That’s the subject of Going Back and Saving.
Game events
These static methods are called on every action at particular moments.
| Method | When |
|---|---|
static async onStart() |
The player presses Start in the main menu. The first statement runs once every action’s and component’s onStart() has finished. |
static async reset() |
A game ends (the end statement, or Quit and its confirmation) and before a save loads. The engine has already emptied every history and put the storage and the label back to their starting values; remove your elements and put your state keys back to their defaults. |
static async onLoad() |
After a save was loaded and its state, histories and storage restored, before the saved statement runs again. Actions run it in groups of equal loadingOrder. |
static async onSave(slot) |
After a game was saved, by the player or an autosave, once the slot is written. slot.key is its name in the storage (Save_3, AutoSave_1) and slot.value what was saved. An error it throws is logged in the console and the save stays. Before 2.9.0 the engine never called it. |
static async beforeRun({ advance }) |
Before every statement the engine runs, whichever action it belongs to. |
static async afterRun({ advance }) |
After every statement’s didApply(). advance says whether it moves on by itself. |
static async beforeRevert({ advance, step }) |
Before every statement the engine undoes. |
static async afterRevert({ advance, step }) |
After every statement’s didRevert(), with what it returned. |
Keep beforeRun() and afterRun() short: they run on every statement of the game.
Everything a save needs has to be in the game’s state, its histories or its storage when the save happens: that’s what a save is made of. onSave() can’t add to a save that is already written; use it for what follows a save, like keeping your own record of when the player last saved.
The base class also has an instance method interrupt() and a static match(), which the engine never calls. Both are deprecated: match statements with matchString() and matchObject().
Reporting problems
While you develop, with engine/debug/debug.js loaded and a debug level above 0, Monogatari shows problems in an error dialog over the game. Your actions can use the same dialog: Monogatari.FancyError. Without the debug module, or with the level at 0, nothing is shown, so remove the debug module when you release your game and players never see these dialogs.
This makes the Flash action point out a duration that isn’t a number, like 'flash fast', and flash for 300 milliseconds anyway. Register the dialog once, next to the action in js/main.js:
Monogatari.FancyError.register('flash:bad_duration', {
title: 'The flash duration "{{duration}}" is not a number',
message: 'A flash statement takes its duration in milliseconds, like \'flash 200\'.',
props: {
'Statement': '{{statement}}',
'Label': '{{label}}',
'Step': '{{step}}',
'Help': {
'_': 'Write the duration with digits only, or leave it out for a 300 millisecond flash.',
},
},
});Then keep the duration as written in the constructor, and check it in a new willApply():
constructor([keyword, duration]) {
super();
this.durationText = duration;
this.duration = parseInt(duration, 10) || 300;
}
async willApply() {
if (typeof this.durationText !== 'undefined' && !/^\d+$/.test(this.durationText)) {
Monogatari.FancyError.show('flash:bad_duration', {
duration: this.durationText,
statement: this._statement,
label: this.engine.state('label'),
step: this.engine.state('step')
});
}
}'flash fast' now opens the dialog, and the game flashes and goes on behind it. The player can’t move on until they close the dialog with Ok.

FancyError.register(id, template)names a dialog once. Start your ids with your game’s or your extension’s name (flash:…), so they can’t clash with the engine’s own (action:jump:label_not_foundand the others).FancyError.show(id, context)shows it, replacing each{{name}}in the template withcontext.name.- In
props, a text becomes a line with its key in bold, a list becomes a bulleted list, and an object becomes a section of its own whose keys starting with_are plain paragraphs. - The title, the message and the values you pass in
contextare shown as text: a value with<in it shows the<. A value can carry one kind of markup, a code block (<code class='language-javascript'>"flash fast"</code>), which the dialog highlights. The template’s ownpropscan hold HTML, such as a link. Before 2.9.0, the values were inserted as HTML.
Monogatari.FancyError.show('A title', 'A message', { 'Detail': 'value' }) works too, without registering a template first.
Related
- Actions: writing, matching and registering an action.
- Going Back and Saving: what happens when the player goes back or loads a save.
- Events: the engine’s events you can listen to.
- Diagnosing Errors: the engine’s own error dialogs.