Skip to content

Instantly share code, notes, and snippets.

@pzuraq
Last active December 31, 2019 13:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pzuraq/5355b33928bd5635e0732bfbf0e0a232 to your computer and use it in GitHub Desktop.
Save pzuraq/5355b33928bd5635e0732bfbf0e0a232 to your computer and use it in GitHub Desktop.
import { get, notifyPropertyChange } from '@ember/object';
export function inLocalStorage(
target,
propertyKey,
descriptor
) {
const targetName = target.constructor.name;
const { initializer } = descriptor;
return {
configurable: true,
enumerable: true,
get() {
const key = `${targetName}-${propertyKey}`;
const lsValue = localStorage.getItem(key);
const json = (lsValue && JSON.parse(lsValue)) || { value: initializer() };
get(this, key);
return json.value;
},
set(value) {
const key = `${targetName}-${propertyKey}`;
const lsValue = JSON.stringify({ value });
localStorage.setItem(key, lsValue);
// this is required to dirty the change tracking system
notifyPropertyChange(this, keys);
},
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment