Web Dev Solutions

Catalin Mititiuc

aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorCatalin Mititiuc <webdevcat@proton.me>2024-05-21 21:05:54 -0700
committerCatalin Mititiuc <webdevcat@proton.me>2024-05-21 21:20:06 -0700
commit7395df376deac945fa8f10cbc05c318b1d8dc931 (patch)
treeee3b24de50fbe82a5612a5164a887b697e2fb513 /src/modules/observable.js
parentd01e0aa92bdedce5c03245e583d096ea5ce1753d (diff)
Remove select callbacks and use observable instead
Diffstat (limited to 'src/modules/observable.js')
-rw-r--r--src/modules/observable.js19
1 files changed, 19 insertions, 0 deletions
diff --git a/src/modules/observable.js b/src/modules/observable.js
new file mode 100644
index 0000000..e4f6797
--- /dev/null
+++ b/src/modules/observable.js
@@ -0,0 +1,19 @@
+const observers = {};
+
+export const Observable = Object.freeze({
+ notify: (event, data) => {
+ observers[event].forEach((observer) => observer(data))
+ },
+
+ subscribe: (event, func) => {
+ (observers[event] ??= []).push(func);
+ },
+
+ unsubscribe: (event, func) => {
+ [...observers[event] || []].forEach((observer, index) => {
+ if (observer === func) {
+ observers[event].splice(index, 1);
+ }
+ });
+ },
+});