From 0eaa356c6cda5ec2da33c219d545fc03e8c70b52 Mon Sep 17 00:00:00 2001 From: hideheader Date: Sat, 7 Mar 2015 02:57:57 -0500 Subject: [PATCH] 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.) --- storage.js | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/storage.js b/storage.js index ccbd2a1e..809ccae7 100644 --- a/storage.js +++ b/storage.js @@ -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) } };