canmove, Confirmed users
2,056
edits
(advise users to avoid namespace collisions) |
(add the Preferences module) |
||
Line 57: | Line 57: | ||
* [http://hg.mozilla.org/labs/weave/index.cgi/file/8e3d60172f32/modules/log4moz.js log4moz.js] - Adorned | * [http://hg.mozilla.org/labs/weave/index.cgi/file/8e3d60172f32/modules/log4moz.js log4moz.js] - Adorned | ||
* [http://hg.mozilla.org/labs/weave/index.cgi/raw-file/8e3d60172f32/modules/log4moz.js log4moz.js] - Raw (right-click to save) | * [http://hg.mozilla.org/labs/weave/index.cgi/raw-file/8e3d60172f32/modules/log4moz.js log4moz.js] - Raw (right-click to save) | ||
== Preferences == | |||
The [http://melez.com/mozilla/modules/Preferences.js Preferences module] provides an API for accessing application preferences. Getting and setting prefs is easy: | |||
let foo = Preferences.get("extensions.test.foo"); | |||
Preferences.set("extensions.test.foo", foo); | |||
As with [http://developer.mozilla.org/en/docs/FUEL:PreferenceBranch FUEL's preferences API], datatypes are auto-detected, and you can pass a default value that the API will return if the pref doesn't have a value: | |||
let foo = Preferences.get("extensions.test.nonexistent", "default value"); | |||
// foo == "default value" | |||
Unlike FUEL, which returns null in the same situation, the module doesn't return a value when you get a nonexistent pref without specifying a default value: | |||
let foo = Preferences.get("extensions.test.nonexistent"); | |||
// typeof foo == "undefined" | |||
(Although the preferences service doesn't currently store null values, other interfaces like nsIVariant and nsIContentPrefService and embedded storage engines like SQLite distinguish between the null value and "doesn't have a value," as does JavaScript, so it seems more consistent and robust to do so here as well.) | |||
=== Look Ma, No XPCOM === | |||
Because we aren't using XPCOM, we can include some interesting API features. First, as you may have noticed already, the interface doesn't require you to create a branch just to get a pref, but you can create one if you want to via an intuitive syntax: | |||
let testBranch = new Preferences("extensions.test."); | |||
// Preferences.get("extensions.test.foo") == testBranch.get("foo") | |||
The get method uses polymorphism to enable you to retrieve multiple values in a single call, and, with JS 1.7's destructuring assignment, you can assign those values to individual variables: | |||
let [foo, bar, baz] = testBranch.get(["foo", "bar", "baz"]); | |||
And <code>set</code> lets you update multiple prefs in one call (although they still get updated individually on the backend, so each change results in a separate notification): | |||
testBranch.set({ foo: 1, bar: "awesome", baz: true }); |