Last active
March 28, 2018 15:05
-
-
Save FabianLauer/ec8e53494877e04d32ca2edbec2e02f6 to your computer and use it in GitHub Desktop.
TypeScript property change trace logs
This file contains 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
/** | |
* Logs information whenever a decorated propery's value is changed. | |
* The log message will contain the previous value, the new value and a stack trace. | |
* @param message An optional message to write to the console when a change is detected. | |
* @example | |
* class Foo { | |
* @tracePropertyChanges('Foo bar') | |
* public bar: any; | |
* } | |
* | |
* const foo = new Foo(); | |
* foo.bar = 123; // will log "CHANGE: Foo bar (bar) ..." | |
*/ | |
export function tracePropertyChanges(message: string = '') { | |
return (target: any, key: string) => { | |
let value: any; | |
Object.defineProperty(target, key, { | |
get: () => value, | |
set: newValue => { | |
// tslint:disable:no-console | |
console.group(`CHANGE: ${message} (${key})`); | |
console.log('from', value, 'to', newValue); | |
console.trace(); | |
console.groupEnd(); | |
// tslint:enable:no-console | |
value = newValue; | |
} | |
}); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment