summaryrefslogtreecommitdiff
path: root/app/infrastructure/event-aggregator.js
blob: eae0e4938d3b87b6eba1b6b9e256944efdfe1c61 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
export default class EventAggregator {
  constructor() {
    this.subscriptions = { };
  }

  subscribe(event, subscriber) {
    this._subscriptionsFor(event).add(subscriber);
  }

  publish(event) {
    this._subscriptionsFor(event.event).forEach((x) => {
      x.notify(event);
    });
  }

  unsubscribe(subscriber) {
    for (var subscription in this.subscriptions) {
      let subscribers = this._subscriptionsFor(subscription)
      if (subscribers.has(subscriber)) {
        subscribers.delete(subscriber);
      }
    }
  }

  _subscriptionsFor(event) {
    let key = event;
    if (!this.subscriptions.hasOwnProperty(key)) {
      this.subscriptions[key] = new Set();
    }
    return this.subscriptions[key];
  }
}