event-target.js 1.7 KB

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