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]

最新文章

  1. Android Gradle Build Error:Some file crunching failed, see logs for details解决办法
  2. 限制帐号同时两处以上登录-ASP.NET
  3. 关于刷Sylvain/burst_ind分支的一些问题解答
  4. AMD 和 CMD as lazy as possible
  5. 飘逸的python - 理解打开文件的模式
  6. PL/SQL — 变长数组
  7. Cygwin编译自己定义OpenCV库报错:opencv_contrib: LOCAL_SRC_FILES points to a missing file
  8. Collecting Bugs poj2096 概率DP
  9. [BZOJ1385] [Baltic2000] Division expression (数学)
  10. Android 自定义控件高度设置onMeasure方法
  11. Win10 - MySQL 5.7 密码重置
  12. PMP:10.项目采购管理
  13. oralce不像Java,java中字符串+数字,能够得到结果字符串
  14. oracle数据库中字符乱码
  15. 求两个数之间的质数 -----------基于for循环 算法思想
  16. [转CSDN多篇文章]WEB 3D SVG CAD 矢量 几种实现方案
  17. go语言学习--语法糖
  18. 自动移动的ImageView
  19. css ::selection 的妙用
  20. soj1767.传纸条

热门文章

  1. 小菜鸟之HTML第一课
  2. STL queue 常见用法详解
  3. 12306火车票余票查询&amp;Python实现邮件发送
  4. php 正则替换特殊字符 和检测是否是中文
  5. wc、iconv命令
  6. T100——按xls格式批量导入数据
  7. (转载)项目中表、类、包、JSP命名规范
  8. Makefile速查笔记
  9. Linux Permission denied 问题
  10. VS2008提示无法打开包括文件:“afxcontrolbars.h”解决办法