[TypeScript] @OnChange for ngOnChanges
2024-09-05 10:38:43
Take away from NGCONF talk.
It is a good show case to how to use decorator.
export interface SimpleChange<T> {
firstChange: boolean;
previousValue: T;
currentValue: T;
isFirstChange: () => boolean;
} function OnChange<T = any>(
callback: (value: T, simpleChange?: SimpleChange<T>) => void
) {
console.log("callback", callback); const cachedValueKey = Symbol();
const isFirstChangeKey = Symbol(); return (target, key) => { Object.defineProperty(target, key, {
set: function(value) {
if (this[isFirstChangeKey] === undefined) {
this[isFirstChangeKey] = true;
} else {
this[isFirstChangeKey] = false;
}
// No operation if new value is same as old value
if (!this[isFirstChangeKey] && this[cachedValueKey] === value) {
return;
} console.log("set value", value); const oldValue = this[cachedValueKey];
this[cachedValueKey] = value;
const simpleChange: SimpleChange<T> = {
firstChange: this[isFirstChangeKey],
previousValue: oldValue,
currentValue: this[cachedValueKey],
isFirstChange: () => this[isFirstChangeKey]
};
callback.call(this, this[cachedValueKey], simpleChange);
},
get: function() {
return this[cachedValueKey];
}
});
};
} class Person {
@OnChange<string>(function(newVal, sc) {
this.trigger(newVal, sc)
})
private name: string = "wan"; trigger (newVal, simpleChange) {
console.log('newVal', newVal);
console.log('simpleChange', simpleChange);
}
} const p = new Person();
p.name = "aa"; // first time, trigger changes
p.name = "aa"; // second time, no trigger
p.name = "bb"; // Trogger changes
One take away is that we can use 'symbol' to uqine key.
const cachedValueKey = Symbol(); this[cachedValueKey]
最新文章
- Android Gradle Build Error:Some file crunching failed, see logs for details解决办法
- 限制帐号同时两处以上登录-ASP.NET
- 关于刷Sylvain/burst_ind分支的一些问题解答
- AMD 和 CMD as lazy as possible
- 飘逸的python - 理解打开文件的模式
- PL/SQL — 变长数组
- Cygwin编译自己定义OpenCV库报错:opencv_contrib: LOCAL_SRC_FILES points to a missing file
- Collecting Bugs poj2096 概率DP
- [BZOJ1385] [Baltic2000] Division expression (数学)
- Android 自定义控件高度设置onMeasure方法
- Win10 - MySQL 5.7 密码重置
- PMP:10.项目采购管理
- oralce不像Java,java中字符串+数字,能够得到结果字符串
- oracle数据库中字符乱码
- 求两个数之间的质数 -----------基于for循环 算法思想
- [转CSDN多篇文章]WEB 3D SVG CAD 矢量 几种实现方案
- go语言学习--语法糖
- 自动移动的ImageView
- css ::selection 的妙用
- soj1767.传纸条