I am looking to streamline my code by creating a set of generic methods to replace backing fields for properties. Specifically, I need to perform some common tasks in the setter (such as calling event emitters in Angular 5) and I want to avoid repeating this code every time.
So far, I have attempted three approaches:
One option is to pass the property name as a string, but I would prefer to find an alternative to this method.
I also experimented with using Error.stack, but found that parsing the stack trace varied among different browsers, which was not ideal.
Upon trying to utilize
arguments.callee.caller
, I encountered the error:
.'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
Do you have any other suggestions for achieving this?
Below is an example usage scenario. Pay attention to the
// somehow get calling property name
comment. Ideally, I would like a solution that returns the string "myProperty"
in this particular case.
class ApplicationComponent {
private readonly properties = new Map<string, any>();
protected getProperty<T>(): T {
const propertyName = // somehow get calling property name
return <T>this.properties[propertyName];
}
protected setProperty<T>(value: T): void {
const propertyName = // somehow get calling property name
const oldValue = <T>this.properties[propertyName];
if (oldValue === value) {
return;
}
this.properties[propertyName] = value;
const eventEmitter = this[`${propertyName}Change`];
if (eventEmitter != null && eventEmitter instanceof EventEmitter) {
eventEmitter.emit(value);
}
}
}
class SomeComponent extends ApplicationComponent {
get myProperty(): SomeType {
return this.getProperty();
}
set myProperty(value: SomeType) {
this.setProperty(value);
}
readonly myPropertyChange = new EventEmitter<SomeType>();
}