|
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 |
|
5 "use strict"; |
|
6 |
|
7 module.metadata = { |
|
8 "stability": "unstable" |
|
9 }; |
|
10 |
|
11 const { Cc, Ci, Cr } = require("chrome"); |
|
12 const { emit, on, off } = require("./core"); |
|
13 const { addObserver } = Cc['@mozilla.org/observer-service;1']. |
|
14 getService(Ci.nsIObserverService); |
|
15 |
|
16 // Simple class that can be used to instantiate event channel that |
|
17 // implements `nsIObserver` interface. It's will is used by `observe` |
|
18 // function as observer + event target. It basically proxies observer |
|
19 // notifications as to it's registered listeners. |
|
20 function ObserverChannel() {} |
|
21 Object.freeze(Object.defineProperties(ObserverChannel.prototype, { |
|
22 QueryInterface: { |
|
23 value: function(iid) { |
|
24 if (!iid.equals(Ci.nsIObserver) && |
|
25 !iid.equals(Ci.nsISupportsWeakReference) && |
|
26 !iid.equals(Ci.nsISupports)) |
|
27 throw Cr.NS_ERROR_NO_INTERFACE; |
|
28 return this; |
|
29 } |
|
30 }, |
|
31 observe: { |
|
32 value: function(subject, topic, data) { |
|
33 emit(this, "data", { |
|
34 type: topic, |
|
35 target: subject, |
|
36 data: data |
|
37 }); |
|
38 } |
|
39 } |
|
40 })); |
|
41 |
|
42 function observe(topic) { |
|
43 let observerChannel = new ObserverChannel(); |
|
44 |
|
45 // Note: `nsIObserverService` will not hold a weak reference to a |
|
46 // observerChannel (since third argument is `true`). There for if it |
|
47 // will be GC-ed with all it's event listeners once no other references |
|
48 // will be held. |
|
49 addObserver(observerChannel, topic, true); |
|
50 |
|
51 return observerChannel; |
|
52 } |
|
53 |
|
54 exports.observe = observe; |