Skip to content

Instantly share code, notes, and snippets.

@albulescu
Created December 15, 2016 21:53
Show Gist options
  • Save albulescu/8a06350813c7bc4be4b9d9b998493ca0 to your computer and use it in GitHub Desktop.
Save albulescu/8a06350813c7bc4be4b9d9b998493ca0 to your computer and use it in GitHub Desktop.
Local Storage Property Binding
export function LocalStorageProperty(property:string) {
return function(target: any, propertyKey: string | symbol) {
var _ref_ = window['Reflect'];
var meta, type;
if(_ref_.getMetadata) {
meta = _ref_.getMetadata('design:type', target, propertyKey);
var result = /^function\s+([\w\$]+)\s*\(/.exec( meta.toString() )
var fnName = result ? result[ 1 ] : '';
if(fnName && fnName.length) {
type = fnName.toLowerCase();
}
}
Object.defineProperty(target, propertyKey, {
get: function() {
var val:any = localStorage.getItem(property);
switch(type) {
case "boolean":
val = (val == "true" || val == "1");
break;
default:
break;
}
return val;
},
set: function(value:any) {
localStorage.setItem(property, value)
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment