precision-game/js/event.mjs
trans_soup b51b776137 rework level loading & restarting, and player death.
level loading is now based on events; the level loading code doesn't
know anything about how things are loaded, it just tells things to load.

player death is also now based on events; instead of directly restarting
the level, it simply sends out an event that the level handling code
listens for.
2023-10-27 12:35:04 +02:00

48 lines
1.3 KiB
JavaScript

const registered_listeners = new Map();
export function trigger (event_name, data) {
for (const callback of listeners(event_name)) {
callback(data);
}
}
export function listen (event_name, callback) {
listeners(event_name).push(callback);
// to find an event later, for deletion or other things.
return [event_name, listeners(event_name).length - 1];
}
// makes a callback function stop being used to listen to an event, and returns that callback function.
export function ignore (listener_id) {
const [event_name, index] = listener_id;
return listeners(event_name).splice(index, 1)[0];
}
function listeners (event_name) {
if (!registered_listeners.has(event_name))
registered_listeners.set(event_name, []);
return registered_listeners.get(event_name);
}
export function attach_listener (target, event_name, callback) {
return listen(event_name, data => {
if (data.target === target) {
callback(data);
}
});
}
export function create_alias (event_name, alias) {
// note that aliases are one-directional; `event_name` isn't triggered when `alias` is.
return listen(event_name, data => trigger(alias, data));
}
export function create_group (group_name, members) {
// TODO: return list of event id:s so groups can be `ignore`:d.
for (const event_name of members) {
create_alias(event_name, group_name);
}
}