summaryrefslogtreecommitdiffstats
path: root/services/cloudsync/CloudSyncEventSource.jsm
blob: edb9c426b292a5bc24812edc8761156286493ba0 (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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

this.EXPORTED_SYMBOLS = ["EventSource"];

Components.utils.import("resource://services-common/utils.js");

var EventSource = function (types, suspendFunc, resumeFunc) {
  this.listeners = new Map();
  for (let type of types) {
    this.listeners.set(type, new Set());
  }

  this.suspend = suspendFunc || function () {};
  this.resume = resumeFunc || function () {};

  this.addEventListener = this.addEventListener.bind(this);
  this.removeEventListener = this.removeEventListener.bind(this);
};

EventSource.prototype = {
  addEventListener: function (type, listener) {
    if (!this.listeners.has(type)) {
      return;
    }
    this.listeners.get(type).add(listener);
    this.resume();
  },

  removeEventListener: function (type, listener) {
    if (!this.listeners.has(type)) {
      return;
    }
    this.listeners.get(type).delete(listener);
    if (!this.hasListeners()) {
      this.suspend();
    }
  },

  hasListeners: function () {
    for (let l of this.listeners.values()) {
      if (l.size > 0) {
        return true;
      }
    }
    return false;
  },

  emit: function (type, arg) {
    if (!this.listeners.has(type)) {
      return;
    }
    CommonUtils.nextTick(
      function () {
        for (let listener of this.listeners.get(type)) {
          listener.call(undefined, arg);
        }
      },
      this
    );
  },
};

this.EventSource = EventSource;