From f9be94762505909d5125b2de272e191796980ad9 Mon Sep 17 00:00:00 2001 From: trans_soup <> Date: Tue, 18 Jul 2023 14:41:26 +0200 Subject: [PATCH] init. code was extracted from another project, so it's already in a somewhat "complete" state. --- export.mjs | 1 + src/core.mjs | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 export.mjs create mode 100644 src/core.mjs diff --git a/export.mjs b/export.mjs new file mode 100644 index 0000000..117605c --- /dev/null +++ b/export.mjs @@ -0,0 +1 @@ +export * from "./src/core.mjs"; diff --git a/src/core.mjs b/src/core.mjs new file mode 100644 index 0000000..da5cd65 --- /dev/null +++ b/src/core.mjs @@ -0,0 +1,48 @@ +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 (event_id) { + const [event_name, index] = event_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); + } +}