|
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 |
|
6 module.metadata = { |
|
7 "stability": "unstable" |
|
8 }; |
|
9 |
|
10 const { Cc, Ci } = require('chrome'); |
|
11 const { Class } = require('../core/heritage'); |
|
12 const { EventTarget } = require('../event/target'); |
|
13 const { Branch } = require('./service'); |
|
14 const { emit, off } = require('../event/core'); |
|
15 const { when: unload } = require('../system/unload'); |
|
16 |
|
17 const prefTargetNS = require('../core/namespace').ns(); |
|
18 |
|
19 const PrefsTarget = Class({ |
|
20 extends: EventTarget, |
|
21 initialize: function(options) { |
|
22 options = options || {}; |
|
23 EventTarget.prototype.initialize.call(this, options); |
|
24 |
|
25 let branchName = options.branchName || ''; |
|
26 let branch = Cc["@mozilla.org/preferences-service;1"]. |
|
27 getService(Ci.nsIPrefService). |
|
28 getBranch(branchName). |
|
29 QueryInterface(Ci.nsIPrefBranch2); |
|
30 prefTargetNS(this).branch = branch; |
|
31 |
|
32 // provides easy access to preference values |
|
33 this.prefs = Branch(branchName); |
|
34 |
|
35 // start listening to preference changes |
|
36 let observer = prefTargetNS(this).observer = onChange.bind(this); |
|
37 branch.addObserver('', observer, false); |
|
38 |
|
39 // Make sure to destroy this on unload |
|
40 unload(destroy.bind(this)); |
|
41 } |
|
42 }); |
|
43 exports.PrefsTarget = PrefsTarget; |
|
44 |
|
45 /* HELPERS */ |
|
46 |
|
47 function onChange(subject, topic, name) { |
|
48 if (topic === 'nsPref:changed') { |
|
49 emit(this, name, name); |
|
50 emit(this, '', name); |
|
51 } |
|
52 } |
|
53 |
|
54 function destroy() { |
|
55 off(this); |
|
56 |
|
57 // stop listening to preference changes |
|
58 let branch = prefTargetNS(this).branch; |
|
59 branch.removeObserver('', prefTargetNS(this).observer, false); |
|
60 prefTargetNS(this).observer = null; |
|
61 } |