Web Dev Solutions

Catalin Mititiuc

aboutsummaryrefslogtreecommitdiff
blob: 65394f693b1db7abab1e33873b8a1c38ad1772db (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);
      }
    });
  },
});