TypeScript之defineProperty實現數據綁定

一:綁定類

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;

三: 結果

TypeScript之defineProperty實現數據綁定

四:結論

此種方案很是簡單, 可是隻能由一個觀察者(這是最大的坑)ide

相關文章
相關標籤/搜索