This repository has been archived on 2025-03-10. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
cetra/lib/core/Emitter.js

57 lines
1.4 KiB
JavaScript
Raw Normal View History

2023-11-19 17:09:28 +00:00
class Emitter {
#listeners;
constructor() {
this.#listeners = new Map();
2023-11-19 17:09:28 +00:00
}
/**
* Registers a callback function for the specified event.
*
* @param {string} event - The name of the event.
* @param {Function} callback - The callback function to be executed when the event is triggered.
*/
on(event, callback) {
if (!this.#listeners.has(event)) {
this.#listeners.set(event, new Set());
2023-11-19 17:09:28 +00:00
}
this.#listeners.get(event).push(callback);
2023-11-19 17:09:28 +00:00
}
/**
* Removes an event listener callback for the specified event.
* If no callback is provided, removes all callbacks for the event.
*
* @param {string} event - The name of the event.
* @param {Function} [callback] - The callback function to be removed.
*/
off(event, callback = undefined) {
if (typeof event != 'string') return;
2023-11-19 17:09:28 +00:00
if (!this.#listeners.has(event)) return false;
2023-11-19 17:09:28 +00:00
if (!callback || this.#listeners.get(event).size === 0) {
return this.#listeners.delete(event);
2023-11-19 17:09:28 +00:00
}
this.#listeners.get(event).delete(callback);
2023-11-19 17:09:28 +00:00
}
/**
* Emits an event and invokes all registered listeners for that event.
*
* @param {string} event - The name of the event to emit.
* @param {...any} args - The arguments to pass to the event listeners.
*/
emit(event, ...args) {
if (!this.#listeners.has(event)) {
2023-11-19 17:09:28 +00:00
return;
}
for (const callback of [...this.#listeners.get(event)]) {
2023-11-19 17:09:28 +00:00
callback(this, ...args);
}
}
}
export default Emitter;