Web Dev Solutions

Catalin Mititiuc

aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
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);
+ }
+ });
+ },
+});