Web Dev Solutions

Catalin Mititiuc

aboutsummaryrefslogtreecommitdiff
blob: c9bea9b5a524ad75c4481db6fc3dc2e32b19c1af (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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);
      }
    });
  },
});