aboutsummaryrefslogtreecommitdiff
path: root/ext/mixed/js
diff options
context:
space:
mode:
authortoasted-nutbread <toasted-nutbread@users.noreply.github.com>2019-11-27 12:00:42 -0500
committertoasted-nutbread <toasted-nutbread@users.noreply.github.com>2019-12-07 13:59:47 -0500
commit20679255b070eb4569107e6e107ec1a1e7c1ab3c (patch)
tree007654747bf51512041e39018dd40beaf4b4b766 /ext/mixed/js
parente99c8c40a1b87e307d5365fe619fa1a71996b500 (diff)
Add class for dispatching custom events
Diffstat (limited to 'ext/mixed/js')
-rw-r--r--ext/mixed/js/core.js46
1 files changed, 46 insertions, 0 deletions
diff --git a/ext/mixed/js/core.js b/ext/mixed/js/core.js
index b5911535..f0c04457 100644
--- a/ext/mixed/js/core.js
+++ b/ext/mixed/js/core.js
@@ -175,3 +175,49 @@ function stringReplaceAsync(str, regex, replacer) {
parts.push(str.substring(index));
return Promise.all(parts).then((v) => v.join(''));
}
+
+
+/*
+ * Common events
+ */
+
+class EventDispatcher {
+ constructor() {
+ this._eventMap = new Map();
+ }
+
+ trigger(eventName, details) {
+ const callbacks = this._eventMap.get(eventName);
+ if (typeof callbacks === 'undefined') { return false; }
+
+ for (const callback of callbacks) {
+ callback(details);
+ }
+ }
+
+ on(eventName, callback) {
+ let callbacks = this._eventMap.get(eventName);
+ if (typeof callbacks === 'undefined') {
+ callbacks = [];
+ this._eventMap.set(eventName, callbacks);
+ }
+ callbacks.push(callback);
+ }
+
+ off(eventName, callback) {
+ const callbacks = this._eventMap.get(eventName);
+ if (typeof callbacks === 'undefined') { return true; }
+
+ const ii = callbacks.length;
+ for (let i = 0; i < ii; ++i) {
+ if (callbacks[i] === callback) {
+ callbacks.splice(i, 1);
+ if (callbacks.length === 0) {
+ this._eventMap.delete(eventName);
+ }
+ return true;
+ }
+ }
+ return false;
+ }
+}