1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/addon-sdk/source/lib/sdk/preferences/event-target.js Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,61 @@ 1.4 +/* This Source Code Form is subject to the terms of the Mozilla Public 1.5 + * License, v. 2.0. If a copy of the MPL was not distributed with this 1.6 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 1.7 +'use strict'; 1.8 + 1.9 +module.metadata = { 1.10 + "stability": "unstable" 1.11 +}; 1.12 + 1.13 +const { Cc, Ci } = require('chrome'); 1.14 +const { Class } = require('../core/heritage'); 1.15 +const { EventTarget } = require('../event/target'); 1.16 +const { Branch } = require('./service'); 1.17 +const { emit, off } = require('../event/core'); 1.18 +const { when: unload } = require('../system/unload'); 1.19 + 1.20 +const prefTargetNS = require('../core/namespace').ns(); 1.21 + 1.22 +const PrefsTarget = Class({ 1.23 + extends: EventTarget, 1.24 + initialize: function(options) { 1.25 + options = options || {}; 1.26 + EventTarget.prototype.initialize.call(this, options); 1.27 + 1.28 + let branchName = options.branchName || ''; 1.29 + let branch = Cc["@mozilla.org/preferences-service;1"]. 1.30 + getService(Ci.nsIPrefService). 1.31 + getBranch(branchName). 1.32 + QueryInterface(Ci.nsIPrefBranch2); 1.33 + prefTargetNS(this).branch = branch; 1.34 + 1.35 + // provides easy access to preference values 1.36 + this.prefs = Branch(branchName); 1.37 + 1.38 + // start listening to preference changes 1.39 + let observer = prefTargetNS(this).observer = onChange.bind(this); 1.40 + branch.addObserver('', observer, false); 1.41 + 1.42 + // Make sure to destroy this on unload 1.43 + unload(destroy.bind(this)); 1.44 + } 1.45 +}); 1.46 +exports.PrefsTarget = PrefsTarget; 1.47 + 1.48 +/* HELPERS */ 1.49 + 1.50 +function onChange(subject, topic, name) { 1.51 + if (topic === 'nsPref:changed') { 1.52 + emit(this, name, name); 1.53 + emit(this, '', name); 1.54 + } 1.55 +} 1.56 + 1.57 +function destroy() { 1.58 + off(this); 1.59 + 1.60 + // stop listening to preference changes 1.61 + let branch = prefTargetNS(this).branch; 1.62 + branch.removeObserver('', prefTargetNS(this).observer, false); 1.63 + prefTargetNS(this).observer = null; 1.64 +}