melonjs-events
Ce qu’il fait
Ce guide explique comment écouter les événements du jeu, comme les mises à jour d'image et les chargements de niveau, et comment arrêter d'écouter. Il s'adresse aux développeurs de jeux qui ont besoin d'une gestion d'événements fiable.
Quand l’utiliser
- ✓Quand un développeur veut que du code s'exécute à chaque image ou lorsqu'un niveau finit de charger.
- ✓Quand le jeu d'un développeur ralentit avec le temps parce que d'anciens écouteurs restent actifs.
- ✓Quand un développeur veut un événement personnalisé pour sa propre logique de jeu.
Lien du skill
https://github.com/melonjs/melonJS/blob/master/packages/melonjs/skills/melonjs-events/SKILL.mdCopiez-le et collez-le dans votre IA (Claude, ChatGPT ou Cursor) en lui demandant de suivre les instructions.
Comment l’utiliser
Le plus simple : copiez le message et collez-le dans votre IA. Elle lit le skill et suit les instructions.
Message prêt à coller
Pour Claude Code, Codex ou Cursor : lancez-la dans le dossier du projet et le skill est installé.
Téléchargez le SKILL.md et placez-le dans le dossier de skills de votre agent.
Exemple de demande à votre IA
“Exécutez mon code quand un niveau a fini de charger dans melonJS, et assurez-vous que je puisse retirer l'écouteur plus tard.”
5 nouveaux skills par semaine. 1 minute de lecture.
Comment ça marche
Le skill demande à l'IA de conserver une référence à chaque gestionnaire ou d'utiliser l'argument de contexte, afin que le même gestionnaire puisse être retiré plus tard.
Contenu technique (SKILL.md original)
Texte original de l’auteur, en anglais, directement depuis GitHub.
Events and lifecycle
The bus
import { event } from "melonjs";
const onUpdate = () => { /* … */ };
const unsubscribe = event.on(event.GAME_UPDATE, onUpdate); // on() returns its own off()
event.once(event.LEVEL_LOADED, () => { /* … */ });
// two ways to undo it — the same reference, or the returned function
event.off(event.GAME_UPDATE, onUpdate);
unsubscribe();
event.on/once/off/has all take an optional third context argument,
invoked as the handler's this. off matches on the pair — handler identity
AND context identity. on(EVT, fn, this) followed by off(EVT, fn) removes
nothing, silently.
Store the handler reference, or use the context argument. An inline arrow or
a fresh .bind(this) in the on call can never be removed — that is the
standard way to leak listeners in melonJS.
// ✗ unremovable
event.on(event.GAME_UPDATE, this.tick.bind(this));
// ✓ keep the bound reference
this._tick = this.tick.bind(this);
event.on(event.GAME_UPDATE, this._tick);
// later: event.off(event.GAME_UPDATE, this._tick);
// ✓ or skip the bind entirely — the context is part of the identity
event.on(event.GAME_UPDATE, this.tick, this);
// later: event.off(event.GAME_UPDATE, this.tick, this);
Custom event names work at runtime (event.emit("my.custom.event", payload)),
but on/emit are typed against a closed map of the engine's own events, so in
TypeScript a name outside that map is a compile error. Use your own emitter for
game events in a .ts project.
The events worth knowing
Per frame
| event | when |
|---|---|
GAME_BEFORE_UPDATE / GAME_UPDATE / GAME_AFTER_UPDATE |
around the world update — GAME_UPDATE is not emitted while paused |
GAME_BEFORE_DRAW / GAME_AFTER_DRAW |
around the draw pass |
WORLD_STEP |
after the physics step |
TICK |
the raw engine tick |
Lifecycle
| event | when |
|---|---|
BOOT, GAME_INIT, VIDEO_INIT |
engine start-up |
STATE_CHANGE, STATE_PAUSE, STATE_RESUME, STATE_STOP |
state machine |
STAGE_RESET |
a stage was reset |
LEVEL_LOADED |
a Tiled level finished loading |
LOADER_PROGRESS, LOADER_COMPLETE, LOADER_ERROR |
asset loading |
BLUR / FOCUS |
the page lost or regained focus |
CANVAS_ONRESIZE, VIEWPORT_ONRESIZE |
relayout hooks |
POINTERMOVE |
global pointer movement |
Use LOADER_PROGRESS / LOADER_COMPLETE. The loader.onProgress /
loader.onload / loader.onError properties were deprecated in 18.2.0 and
removed in 20.3: they were module-level let bindings on an ES module
namespace, so loader.onProgress = fn threw and the documented migration path
never worked. For completion, loader.preload(assets, onloadcb) also takes the
callback directly.
Renderable lifecycle callbacks
Prefer these over bus subscriptions where they fit — the engine calls them at the right times and there is nothing to unsubscribe:
| callback | when |
|---|---|
onActivateEvent() |
addChild-ed into a container that is already attached to the world root (a Container forwards it to its children) |
onDeactivateEvent() |
removed from its container — including the automatic world clear on a state change |
onDestroyEvent() |
destroy() ran; called with no arguments from the container-removal path |
onCollisionStart / onCollisionActive / onCollisionEnd |
contacts |
Note the activate gate: adding a child to a detached container fires nothing.
The callback arrives later, when that container itself is added to the world.
And an isPersistent renderable survives the world clear between stages, so it
gets no fresh onActivateEvent on the next state.
Pair subscriptions with activate/deactivate, not the constructor. This is the rule that keeps pooled objects working:
onActivateEvent() {
this._tick = this.update.bind(this);
event.on(event.GAME_UPDATE, this._tick);
input.registerPointerEvent("pointerdown", this, this._onDown);
}
onDeactivateEvent() {
event.off(event.GAME_UPDATE, this._tick);
input.releasePointerEvent("pointerdown", this);
}
Pool-recycled objects never fire onDestroyEvent on removal — removeChildNow
first tries to return the child to the pool that built it, and only calls
destroy() when nothing owns it. So anything taken from a createPool goes
back to that pool instead. Anything you clean up there will not run. destroy() is also what calls
releaseAllPointerEvents(this), which is why a
Questions fréquentes
Pourquoi event.off ne fonctionne-t-il pas ?
Le skill indique que la suppression correspond à la fois au gestionnaire et à son contexte, il faut donc fournir le même couple.
Pourquoi les écouteurs s'accumulent-ils ?
Une fonction fléchée en ligne ou un nouvel appel bind ne peut pas être retiré plus tard, le skill recommande donc de stocker la référence.
Puis-je créer mes propres événements ?
Oui. Des noms d'événements personnalisés fonctionnent à l'exécution, même si la liste typée couvre les événements propres au moteur.
Détails
Description originale de l’auteur
Use this skill for the melonJS event bus and lifecycle hooks — subscribing to engine events, the per-frame and per-state event names, renderable lifecycle callbacks, and how to unsubscribe without leaking. Triggers on: event.on, event.off, event.once, event.emit, GAME_UPDATE, GAME_BEFORE_DRAW, LEVEL_LOADED, LOADER_COMPLETE, STATE_CHANGE, CANVAS_ONRESIZE, POINTERMOVE, WORLD_STEP, onActivateEvent, onDeactivateEvent, onDestroyEvent, lifecycle, subscribe, listener.
repo: melonjs/melonJS
Popularité
- Étoiles GitHub
- 6.4k
- Position au classement
- #14202
- Licence
- MIT
- Mis à jour
- 02/11/2026
Commentaires
- …
Autres skills de ce dépôt
melonjs-20-migration
6.4kAide votre agent à écrire du code de jeu melonJS pour la version 20 et à éviter les méthodes obsolètes des versions précédentes, comme le démarrage asynchrone obligatoire.
melonjs-3d-assets
6.4kAide votre agent à charger des modèles 3D comme les fichiers glTF, GLB et OBJ dans un jeu melonJS, avec des options d'échelle et d'éclairage.
melonjs-3d
6.4kAide votre agent à construire des scènes 3D ou 2,5D dans un jeu melonJS, avec les caméras, les maillages, les lumières et la profondeur, selon les règles d'axes du moteur.
melonjs-audio
6.4kAide votre agent à ajouter des effets sonores et de la musique à un jeu melonJS, avec la configuration audio, les pistes de fond, le réglage du volume et le son spatial.
Skills similaires
diffs
394kPermet à votre agent de produire un diff réel et partageable de vos modifications, sous forme de lien ou d'image, plutôt qu'un résumé écrit à la main.
coding-agent
394kAide votre agent à confier une tâche de programmation plus importante à Codex, Claude Code ou OpenCode comme travailleur en arrière-plan, puis à suivre sa progression.
gh-issues
394kAide votre agent à trouver des tickets GitHub, choisir ceux à traiter et ouvrir des pull requests avec des correctifs, y compris le suivi des commentaires de relecture.