init.
code was extracted from another project, so it's already in a somewhat "complete" state.
This commit is contained in:
commit
f9be947625
2 changed files with 49 additions and 0 deletions
1
export.mjs
Normal file
1
export.mjs
Normal file
|
@ -0,0 +1 @@
|
|||
export * from "./src/core.mjs";
|
48
src/core.mjs
Normal file
48
src/core.mjs
Normal file
|
@ -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);
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue