Component Life Cycle
A component has two sets of methods:
- The element’s methods (
async didMount()) run for each element: when it’s created, put on the page, rendered, updated and taken off the page. Pandora, the library Monogatari’s components are built on, calls them. - The class’s methods (
static async setup()) run once, or on every registered component at the same moment of the game. The engine calls them, as it does an action’s.
Inside both, this.engine is the engine.
The element’s life cycle
When the element goes on the page, Monogatari’s Component also adds the animated class to it, and Pandora sets data-component to the tag. In the page, the AffectionMeter from Components looks like this:
<affection-meter max="5" class="animated" data-component="affection-meter">
<span class="affection-meter__label">Affection</span>
<span class="affection-meter__value">0 / 5</span>
</affection-meter>The constructor
Call super() first. Give props and state their starting values by assigning whole objects:
constructor() {
super();
this.props = {
mode: 'adv'
};
this.state = {
hidden: false
};
}That’s only allowed before the element is on the page. Afterwards, assigning this.state throws “Component state should be set using the setState function instead.”, and changing a single prop (this.props.mode = 'nvl') always throws; use setState() and setProps().
Don’t set attributes in the constructor, and don’t call setProps() there, which sets them: see the warning in Components an action creates.
async willMount()
Runs each time the element goes on the page, before it renders. The built-in screens use it to set their data-screen attribute.
render()
Returns the component’s markup as a string, or a promise of one: async render() works, and the built-in <text-box> uses it. What Pandora does with the result:
- An empty string leaves the element’s content as it is. That’s what
ScreenComponentreturns by default, so a screen keeps the children written inside it inindex.html. - Any other string replaces the element’s content. Then, unless the string already contains them, the children written inside the element in
index.htmlare added after it.
When the component has a template, set with template() or with a <template> tag in index.html, Pandora renders the template instead of calling render(). See Changing Built-in Components.
async didMount() and async didReconnect()
didMount() runs once per element, after its first render: add listeners and start timers here. When the same element is taken off the page and put back, didReconnect() runs instead.
ready(callback)
Calls callback once the element has rendered for the first time, or right away when it already has. Use it after you put an element on the page and need its markup:
const card = document.createElement('title-card');
this.engine.element().find('[data-screen="game"]').append(card);
card.ready(() => {
card.querySelector('h2').classList.add('fadeIn');
});Children written in index.html
The first time the element goes on the page, Pandora keeps the HTML written between its tags in this.slotContent. By default it ends up after what render() returns. To put it somewhere else, write it into the markup:
class ChapterBox extends Monogatari.Component {
static tag = 'chapter-box';
render() {
return `
<header>Chapter</header>
<div class="chapter-box__body">${this.slotContent}</div>
`;
}
}
monogatari.registerComponent(ChapterBox);<chapter-box><p>Inside</p></chapter-box> renders as <header>Chapter</header><div class="chapter-box__body"><p>Inside</p></div>.
A <slot> element in render() doesn’t do this for a Component: the children still end up after the markup, and the next render puts the new markup inside the old one. Slots only work in a ShadowComponent.
async willUnmount(), async unmount() and async didUnmount()
Run in that order when the element is taken off the page. Remove here what didMount() added outside the element: listeners on the engine or on window, intervals, timers.
Updating a component
setState() and setProps() merge an object into the component’s state or props. For each key in it, Pandora then runs:
willUpdate(origin, property, oldValue, newValue, oldObject, newObject)update(…), with the same argumentsonStateUpdate(property, oldValue, newValue, oldObject, newObject)for a state change,onPropsUpdate(…)for a propdidUpdate(…)
origin is 'state' or 'props'. None of them renders the component again: call forceRender() when the markup should change.
class ClueCounter extends Monogatari.Component {
static tag = 'clue-counter';
constructor() {
super();
this.state = { clues: 0 };
}
async onStateUpdate(property) {
if (property === 'clues') {
await this.forceRender();
}
}
render() {
return `<span>${this.state.clues} clues</span>`;
}
}
monogatari.registerComponent(ClueCounter);document.querySelector('clue-counter').setState({ clues: 2 }) changes the text to “2 clues”. Without the onStateUpdate() method, the state changes and the text stays “0 clues”.
setProps() also writes every text, number and boolean prop to an attribute of the same name, so CSS can select on it: the built-in <text-box> gets mode="adv" or mode="nvl".
The engine’s class methods
The engine calls these static methods on every registered component, the same way it calls an action’s mounting methods, during monogatari.init():
| Method | When |
|---|---|
static async setup(selector) |
First phase of monogatari.init(), right after the engine defines the components. selector is what monogatari.init() was given. |
static async bind(selector) |
Second phase. Attach listeners on the game’s element here. |
static async init(selector) |
Third phase, once every component and action is set up and bound. |
Game hooks
These are static methods too. The base class’s versions of most of them call a method of the same name on every element of the component that’s on the page, so you can write either the static method, for the class as a whole, or the instance method, for each element.
| Static method | When | Calls on each element |
|---|---|---|
shouldProceed(options) |
The game is about to move on. Throw or reject to refuse. | shouldProceed(), without the options |
willProceed() |
Nothing refused, and the next statement is about to run. | willProceed() |
shouldRollback() |
The player pressed Back. Throw or reject to refuse. | shouldRollback() |
willRollback() |
Nothing refused going back. | willRollback() |
onReset() |
A game ends, and before a save loads. | onReset() |
onStart() |
The player presses Start. | nothing |
onLoad() |
A save has been loaded, before the saved statement runs again. | nothing |
onSave(slot) |
A game was saved, by the player or an autosave, once the slot is written: slot.key is its name in the storage, slot.value what was saved. An error it throws is logged and the save stays. Before 2.9.0 it was never called. |
nothing |
The arguments and the rules are the ones actions follow: Action Life Cycle.
Listening to engine events
this.engine.on('didUpdateState', callback) listens to an engine event on the game’s <visual-novel> element, and this.engine.off('didUpdateState', callback) stops listening. Pass off() the same function you passed on(), so keep it in a field, as the AffectionMeter does with refresh, and pair the two calls in didMount() and willUnmount().
When a component throws
An error thrown in willMount(), render() or didMount() stops that element’s mount: it stays empty or half-drawn. With the debug module loaded, an error dialog titled “Error in component <affection-meter> during connectedCallback” shows the error’s message, and the console shows “[Monogatari] Component error in <affection-meter> during connectedCallback” with the error. The same happens for errors in willUnmount(), unmount() and didUnmount(), as “during disconnectedCallback”.
Related
- Components: writing and registering a component.
- Component Reference: every property and method.
- Core Libraries: Pandora, the library behind the life cycle.