services/cloudsync/CloudSyncEventSource.jsm
author Phil Ringnalda <philringnalda@gmail.com>
Sun, 18 Jan 2015 19:53:21 -0800
changeset 224464 13834f7f5c6c1d69ce32c709f9d4418b015e26c8
parent 202633 2df073cb512c562a9b74d40858db73bef0ff511f
child 262599 380817d573cdfbfc4a4b4a4647cf1a53bb52c3b9
permissions -rw-r--r--
Bug 788999 followup, reenable test_fileapi_slice.html on OS X 10.8 since whatever caused it to hang two years ago seems to be gone

/* 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");

let EventSource = function (types, suspendFunc, resumeFunc) {
  this.listeners = new Map();
  for each (let type in 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;