Events

A simple event system. Allows you to hook into Kontra lifecycle events or create your own, such as for Plugins.

let { on, off, emit } = kontra;

function callback(a, b, c) {
  console.log({a, b, c});
});

on('myEvent', callback);
emit('myEvent', 1, 2, 3);  //=> {a: 1, b: 2, c: 3}
off('myEvent', callback);
import { on, off, emit } from 'path/to/kontra.mjs';

function callback(a, b, c) {
  console.log({a, b, c});
});

on('myEvent', callback);
emit('myEvent', 1, 2, 3);  //=> {a: 1, b: 2, c: 3}
off('myEvent', callback);
import { on, off, emit } from 'kontra';

function callback(a, b, c) {
  console.log({a, b, c});
});

on('myEvent', callback);
emit('myEvent', 1, 2, 3);  //=> {a: 1, b: 2, c: 3}
off('myEvent', callback);

Table of Contents

Lifecycle Events

There are currently only three lifecycle events:

  • init - Emitted after kontra.init() is called.
  • tick - Emitted every frame of GameLoop before the loops update() and render() functions are called.
  • assetLoaded - Emitted after an asset has fully loaded using the asset loader. The callback function is passed the asset and the url of the asset as parameters.

emit(​event, ...args)

Call all callback functions for the event. All arguments will be passed to the callback functions.

emit Parameters

event

String. Name of the event.

...args

A list of any type. Comma separated list of arguments passed to all callbacks.

off(​event, callback)

Remove a callback for an event.

off Parameters

event

String. Name of the event.

callback

Function. The function that was passed during registration.

on(​event, callback)

Register a callback for an event to be called whenever the event is emitted. The callback will be passed all arguments used in the emit call.

on Parameters

event

String. Name of the event.

callback

Function. Function that will be called when the event is emitted.