michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: "use strict"; michael@0: michael@0: module.metadata = { michael@0: "stability": "unstable" michael@0: }; michael@0: michael@0: const { Cc, Ci, Cr } = require("chrome"); michael@0: const { emit, on, off } = require("./core"); michael@0: const { addObserver } = Cc['@mozilla.org/observer-service;1']. michael@0: getService(Ci.nsIObserverService); michael@0: michael@0: // Simple class that can be used to instantiate event channel that michael@0: // implements `nsIObserver` interface. It's will is used by `observe` michael@0: // function as observer + event target. It basically proxies observer michael@0: // notifications as to it's registered listeners. michael@0: function ObserverChannel() {} michael@0: Object.freeze(Object.defineProperties(ObserverChannel.prototype, { michael@0: QueryInterface: { michael@0: value: function(iid) { michael@0: if (!iid.equals(Ci.nsIObserver) && michael@0: !iid.equals(Ci.nsISupportsWeakReference) && michael@0: !iid.equals(Ci.nsISupports)) michael@0: throw Cr.NS_ERROR_NO_INTERFACE; michael@0: return this; michael@0: } michael@0: }, michael@0: observe: { michael@0: value: function(subject, topic, data) { michael@0: emit(this, "data", { michael@0: type: topic, michael@0: target: subject, michael@0: data: data michael@0: }); michael@0: } michael@0: } michael@0: })); michael@0: michael@0: function observe(topic) { michael@0: let observerChannel = new ObserverChannel(); michael@0: michael@0: // Note: `nsIObserverService` will not hold a weak reference to a michael@0: // observerChannel (since third argument is `true`). There for if it michael@0: // will be GC-ed with all it's event listeners once no other references michael@0: // will be held. michael@0: addObserver(observerChannel, topic, true); michael@0: michael@0: return observerChannel; michael@0: } michael@0: michael@0: exports.observe = observe;