chrome.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. "use strict";
  5. module.metadata = {
  6. "stability": "unstable"
  7. };
  8. const { Cc, Ci, Cr } = require("chrome");
  9. const { emit, on, off } = require("./core");
  10. const { addObserver } = Cc['@mozilla.org/observer-service;1'].
  11. getService(Ci.nsIObserverService);
  12. // Simple class that can be used to instantiate event channel that
  13. // implements `nsIObserver` interface. It's will is used by `observe`
  14. // function as observer + event target. It basically proxies observer
  15. // notifications as to it's registered listeners.
  16. function ObserverChannel() {}
  17. Object.freeze(Object.defineProperties(ObserverChannel.prototype, {
  18. QueryInterface: {
  19. value: function(iid) {
  20. if (!iid.equals(Ci.nsIObserver) &&
  21. !iid.equals(Ci.nsISupportsWeakReference) &&
  22. !iid.equals(Ci.nsISupports))
  23. throw Cr.NS_ERROR_NO_INTERFACE;
  24. return this;
  25. }
  26. },
  27. observe: {
  28. value: function(subject, topic, data) {
  29. emit(this, "data", {
  30. type: topic,
  31. target: subject,
  32. data: data
  33. });
  34. }
  35. }
  36. }));
  37. function observe(topic) {
  38. let observerChannel = new ObserverChannel();
  39. // Note: `nsIObserverService` will not hold a weak reference to a
  40. // observerChannel (since third argument is `true`). There for if it
  41. // will be GC-ed with all it's event listeners once no other references
  42. // will be held.
  43. addObserver(observerChannel, topic, true);
  44. return observerChannel;
  45. }
  46. exports.observe = observe;