Created
December 31, 2019 13:59
-
-
Save pzuraq/06e338c0395566f492cbb62c0adcb60d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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