一:绑定类
class CommonTools {
public static watch<T>(obj: Object, name: string, callback: ($data: T) => void, init: boolean = true): void {
let $value: T = obj[name] as T;
Object.defineProperty(obj, name, {
get() { return $value },
set($newValue) {
if ($value != $newValue) {
$value = $newValue;
callback($value);
}
}
});
init && callback($value);
}
}
二:测试
class M {
private k: number = 10;
}
window["a"] = new M();
CommonTools.watch<number>(window["a"], "k", ($data: number) => {
console.log(`aaaa : ${$data}`);
}, true);
window["a"].k = 12;
CommonTools.watch<number>(window["a"], "k", ($data: number) => {
console.log(`bbb : ${$data}`);
}, true);
window["a"].k = 13;
三: 结果
四:结论
此种方案非常简单, 但是只能由一个观察者(这是最大的坑)
来源:oschina
链接:https://my.oschina.net/u/4408224/blog/3234052