Preferences improvements

(1) An element's `change` listener can be used to initialize what it's
controlling. `loadPrefs` sends a `change` event to the element
after setting the element `value` but before adding its own `change`
listener. Add the element's listener before calling `loadPrefs` to receive
the synthetic event.
(2) `prefs.setPref` only broadcasts a notification if the value returned
by `getPref` changes.
(3) A user preference with the same (typed) value as the default is
evicted from `localStorage`. (Firefox does this.)
This commit is contained in:
hideheader 2015-03-07 02:57:57 -05:00
parent 6ec65ab9e9
commit 0eaa356c6c

View File

@ -151,6 +151,7 @@ function loadPrefs(prefs) {
} else {
el.value = value;
}
el.dispatchEvent(new Event("change", {bubbles: true, cancelable: true}));
el.addEventListener("change", changePref);
}
}
@ -191,10 +192,20 @@ var prefs = {
},
setPref: function(key, value) {
if (!(key in this)) console.warn(this.NO_DEFAULT_PREFERENCE, key);
if (value === undefined) localStorage.removeItem(key);
else localStorage.setItem(key, "string" === typeof value ? value : JSON.stringify(value));
var oldValue = this.getPref(key);
notifyAllTabs({method: "prefChanged", prefName: key, value: value});
if (undefined === value || this[key] === value) {
localStorage.removeItem(key); // (deleted || default)
} else {
var strValue = ("string" === typeof value ||
undefined === value) ? value : JSON.stringify(value);
localStorage.setItem(key, strValue);
}
var newValue = this.getPref(key);
if (newValue !== oldValue) {
notifyAllTabs({method: "prefChanged", prefName: key, value: value});
}
},
removePref: function(key) { setPref(key, undefined) }
};