Skip to content

Instantly share code, notes, and snippets.

@pzuraq
Created December 31, 2019 13:59
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/06e338c0395566f492cbb62c0adcb60d to your computer and use it in GitHub Desktop.
Save pzuraq/06e338c0395566f492cbb62c0adcb60d to your computer and use it in GitHub Desktop.
import { createTag, dirtyTag, consumeTag } from '@glimmer/tracking/tags';
export function inLocalStorage(
target,
propertyKey,
descriptor
) {
const targetName = target.constructor.name;
const key = `${targetName}-${propertyKey}`;
const { initializer } = descriptor;
let tags = new WeakMap();
return {
configurable: true,
enumerable: true,
get() {
const lsValue = localStorage.getItem(key);
const json = (lsValue && JSON.parse(lsValue)) || { value: initializer() };
let tag = tags.get(this);
if (!tag) {
tag = createTag();
tags.set(this, tag);
}
consumeTag(tag);
return json.value;
},
set(value) {
const lsValue = JSON.stringify({ value });
localStorage.setItem(key, lsValue);
if (tags.has(this)) {
dirtyTag(tags.get(this));
}
},
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment