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: 'use strict'; michael@0: michael@0: module.metadata = { michael@0: "stability": "unstable" michael@0: }; michael@0: michael@0: const { Cc, Ci } = require('chrome'); michael@0: const { Class } = require('../core/heritage'); michael@0: const { EventTarget } = require('../event/target'); michael@0: const { Branch } = require('./service'); michael@0: const { emit, off } = require('../event/core'); michael@0: const { when: unload } = require('../system/unload'); michael@0: michael@0: const prefTargetNS = require('../core/namespace').ns(); michael@0: michael@0: const PrefsTarget = Class({ michael@0: extends: EventTarget, michael@0: initialize: function(options) { michael@0: options = options || {}; michael@0: EventTarget.prototype.initialize.call(this, options); michael@0: michael@0: let branchName = options.branchName || ''; michael@0: let branch = Cc["@mozilla.org/preferences-service;1"]. michael@0: getService(Ci.nsIPrefService). michael@0: getBranch(branchName). michael@0: QueryInterface(Ci.nsIPrefBranch2); michael@0: prefTargetNS(this).branch = branch; michael@0: michael@0: // provides easy access to preference values michael@0: this.prefs = Branch(branchName); michael@0: michael@0: // start listening to preference changes michael@0: let observer = prefTargetNS(this).observer = onChange.bind(this); michael@0: branch.addObserver('', observer, false); michael@0: michael@0: // Make sure to destroy this on unload michael@0: unload(destroy.bind(this)); michael@0: } michael@0: }); michael@0: exports.PrefsTarget = PrefsTarget; michael@0: michael@0: /* HELPERS */ michael@0: michael@0: function onChange(subject, topic, name) { michael@0: if (topic === 'nsPref:changed') { michael@0: emit(this, name, name); michael@0: emit(this, '', name); michael@0: } michael@0: } michael@0: michael@0: function destroy() { michael@0: off(this); michael@0: michael@0: // stop listening to preference changes michael@0: let branch = prefTargetNS(this).branch; michael@0: branch.removeObserver('', prefTargetNS(this).observer, false); michael@0: prefTargetNS(this).observer = null; michael@0: }