Commit 4f0dbb9b authored by Robert Knight's avatar Robert Knight

Use `watch` utility to simplify persisted-defaults service

parent 5888fd96
import { watch } from '../util/watch';
/** /**
* A service for reading and persisting convenient client-side defaults for * A service for reading and persisting convenient client-side defaults for
* the (browser) user. * the (browser) user.
...@@ -10,14 +12,11 @@ const DEFAULT_KEYS = { ...@@ -10,14 +12,11 @@ const DEFAULT_KEYS = {
// @ngInject // @ngInject
export default function persistedDefaults(localStorage, store) { export default function persistedDefaults(localStorage, store) {
let lastDefaults;
/** /**
* Store subscribe callback for persisting changes to defaults. It will only * Store subscribe callback for persisting changes to defaults. It will only
* persist defaults that it "knows about" via `DEFAULT_KEYS`. * persist defaults that it "knows about" via `DEFAULT_KEYS`.
*/ */
function persistChangedDefaults() { function persistChangedDefaults(latestDefaults, lastDefaults) {
const latestDefaults = store.getDefaults();
for (let defaultKey in latestDefaults) { for (let defaultKey in latestDefaults) {
if ( if (
lastDefaults[defaultKey] !== latestDefaults[defaultKey] && lastDefaults[defaultKey] !== latestDefaults[defaultKey] &&
...@@ -29,7 +28,6 @@ export default function persistedDefaults(localStorage, store) { ...@@ -29,7 +28,6 @@ export default function persistedDefaults(localStorage, store) {
); );
} }
} }
lastDefaults = latestDefaults;
} }
return { return {
...@@ -45,10 +43,9 @@ export default function persistedDefaults(localStorage, store) { ...@@ -45,10 +43,9 @@ export default function persistedDefaults(localStorage, store) {
const defaultValue = localStorage.getItem(DEFAULT_KEYS[defaultKey]); const defaultValue = localStorage.getItem(DEFAULT_KEYS[defaultKey]);
store.setDefault(defaultKey, defaultValue); store.setDefault(defaultKey, defaultValue);
}); });
lastDefaults = store.getDefaults();
// Listen for changes to those defaults from the store and persist them // Listen for changes to those defaults from the store and persist them
store.subscribe(persistChangedDefaults); watch(store.subscribe, () => store.getDefaults(), persistChangedDefaults);
}, },
}; };
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment