melonjs-events
O que ela faz
Explica como escutar eventos do jogo, como atualizações de quadro e carregamentos de nível, e como parar de escutar. É para desenvolvedores de jogos que precisam de um tratamento de eventos confiável.
Quando usar
- ✓Quando um desenvolvedor quer que um código rode a cada quadro ou quando um nível termina de carregar.
- ✓Quando o jogo de um desenvolvedor fica mais lento com o tempo porque ouvintes antigos continuam ativos.
- ✓Quando um desenvolvedor quer um evento personalizado para a lógica do próprio jogo.
Link da skill
https://github.com/melonjs/melonJS/blob/master/packages/melonjs/skills/melonjs-events/SKILL.mdCopie e cole na sua IA (Claude, ChatGPT ou Cursor) pedindo para seguir as instruções.
Como usar
O jeito mais fácil: copie a mensagem e cole na sua IA. Ela lê a skill e segue as instruções.
Mensagem pronta para colar
Para Claude Code, Codex ou Cursor: rode na pasta do projeto e a skill fica instalada.
Baixe o SKILL.md e coloque na pasta de skills do seu agente.
Exemplo do que pedir para a IA
“Execute meu código quando um nível terminar de carregar no melonJS e garanta que eu possa remover o ouvinte depois.”
5 skills novas por semana. 1 minuto de leitura.
Como funciona
A skill orienta a IA a manter uma referência a cada manipulador ou usar o argumento de contexto, para que o mesmo manipulador possa ser removido depois.
Conteúdo técnico (SKILL.md original)
Texto original do autor, em inglês, direto do 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
Perguntas frequentes
Por que event.off não funciona?
A skill diz que a remoção depende do manipulador e do contexto, então o mesmo par precisa ser informado.
Por que os ouvintes se acumulam?
Uma função de seta inline ou uma nova chamada de bind não pode ser removida depois, então a skill recomenda guardar a referência.
Posso criar meus próprios eventos?
Sim. Nomes de eventos personalizados funcionam em tempo de execução, embora a lista tipada cubra os eventos do próprio motor.
Detalhes
Descrição original do autor
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
Popularidade
- Estrelas no GitHub
- 6,4 mil
- Posição no ranking
- #14202
- Licença
- MIT
- Atualizada em
- 02/11/2026
Comentários
- …
Mais skills deste repositório
melonjs-20-migration
6,4 milAjuda seu agente a escrever código de jogo em melonJS para a versão 20 e a evitar métodos desatualizados de versões antigas, como a inicialização assíncrona obrigatória.
melonjs-3d-assets
6,4 milAjuda seu agente a carregar modelos 3D, como arquivos glTF, GLB e OBJ, em um jogo melonJS para navegador, com opções de escala e iluminação.
melonjs-3d
6,4 milAjuda seu agente a criar cenas 3D ou 2,5D em um jogo melonJS para navegador, cobrindo câmeras, malhas, luzes e profundidade, usando as regras de eixos do próprio motor.
melonjs-audio
6,4 milAjuda seu agente a adicionar efeitos sonoros e músicas a um jogo melonJS, incluindo a configuração de áudio, faixas de fundo, controle de volume e som espacial.
Skills parecidas
diffs
394 milPermite que seu agente gere um diff real e compartilhável das edições, como link de visualização ou arquivo de imagem, em vez de um resumo escrito à mão.
coding-agent
394 milAjuda seu agente a passar um trabalho grande de programação para o Codex, Claude Code ou OpenCode em segundo plano e acompanhar o andamento.
gh-issues
394 milAjuda seu agente a encontrar issues do GitHub, escolher quais resolver e abrir pull requests com correções, acompanhando os comentários de revisão.