【发布时间】:2018-04-17 12:09:20
【问题描述】:
我想用 TypeScript Decorator 创建一个属性 getter 和 setter,但我坚持定义在更改或请求属性时要运行的函数。
如果我的Field.watch 装饰器有以下用法:
export class Test {
...
@Field.watch({onSet: this.resetCssCache})
public layoutId = 0;
...
public resetCssCache() {
...
}
...
}
装饰器的实现是:
export class Field {
public static watch(watchers: { onGet?: () => any, onSet?: (newValue: any, oldValue: any) => any }): Function {
return (target: any, key: string) => {
// property getter
const getter = function() {
return this['_' + key];
};
// property setter
const setter = function(newVal) {
if (watchers.onSet) {
this['_' + key] = watchers.onSet(newVal, this['_' + key]);
}
this['_' + key] = newVal;
};
// Delete property.
if (delete this[key]) {
// Create new property with getter and setter
Object.defineProperty(target, key, {
get: getter,
set: setter,
enumerable: true,
configurable: true
});
}
}
}
}
我在@Field.watch({onSet: this.resetCssCache}) 上收到一个错误,告诉我this 没有定义。
我猜装饰器是在定义级别而不是实例级别上解释的。 有没有办法将非静态方法绑定到我的装饰器的 onSet 属性?
【问题讨论】:
标签: typescript decorator