kontra
Version:
Kontra HTML5 game development library
64 lines (58 loc) • 1.88 kB
JavaScript
/**
* A simple event system, mostly created to support [Plugins](api/plugin). Allows you to hook into Kontra lifecycle events or create your own.
*
* ```js
* 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);
* ```
* @sectionName Events
*/
// expose for testing
export let callbacks = {};
/**
* There are currently only two lifecycle events:
* - `init` - Emitted after `init()` is called.
* - `tick` - Emitted every frame of kontra.GameLoop before the loops `update()` and `render()` functions are called.
* @sectionName Lifecycle Events
*/
/**
* 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.
* @function on
*
* @param {String} event - Name of the event.
* @param {Function} callback - Function that will be called when the event is emitted.
*/
export function on(event, callback) {
callbacks[event] = callbacks[event] || [];
callbacks[event].push(callback);
}
/**
* Remove a callback for an event.
* @function off
*
* @param {String} event - Name of the event.
* @param {Function} callback - The function that was passed during registration.
*/
export function off(event, callback) {
let index;
if (!callbacks[event] || (index = callbacks[event].indexOf(callback)) < 0) return;
callbacks[event].splice(index, 1);
}
/**
* Call all callback functions for the event. All arguments will be passed to the callback functions.
* @function emit
*
* @param {String} event - Name of the event.
* @param {*} [args] - Arguments passed to all callbacks.
*/
export function emit(event, ...args) {
if (!callbacks[event]) return;
callbacks[event].map(fn => fn(...args));
}