Created
June 22, 2020 08:19
-
-
Save theredhead/e49ffa7bf85d623d39499a98ada4bc66 to your computer and use it in GitHub Desktop.
Annotate a field in a typescript class to store its' content in localstorage transparently.
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
// | |
// Inspired by https://github.com/zhaosiyang/property-watch-decorator/blob/master/src/index.ts | |
// | |
// Annotate a field in a typescript class to store its' content in localstorage transparently. | |
// | |
export function Preference<T = any>(preferenceKey: string, defaultValueObj: T) { | |
return (target: any, key: PropertyKey) => { | |
Object.defineProperty(target, key, { | |
set: function(value) { | |
localStorage.setItem(preferenceKey, JSON.stringify(value)); | |
}, | |
get: function() { | |
const rawValue = window.localStorage.getItem(preferenceKey); | |
const value = rawValue !== null && rawValue !== undefined ? <T>JSON.parse(rawValue) : defaultValueObj; | |
return value; | |
}, | |
}); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment