-
Notifications
You must be signed in to change notification settings - Fork 1
/
mod.ts
31 lines (25 loc) · 878 Bytes
/
mod.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Copyright 2019 Jason Zi Feng Lei. All rights reserved. MIT license.
interface OptionsStruct {
callbackOnGet?: Boolean;
}
export function watch(obj: Object, cb: Function, opt?: OptionsStruct): Object {
const traps: Object = {
get: (target: Object, property: any, receiver: any) => {
if (opt && opt.callbackOnGet === true) cb();
const value: any = Reflect.get(target, property, receiver);
if (typeof value === 'object' && value !== null) {
return new Proxy(value, traps);
}
return value;
},
defineProperty: (target: Object, property: any, descriptor: any) => {
cb();
return Reflect.defineProperty(target, property, descriptor);
},
deleteProperty: (target: Object, property: any) => {
cb();
return Reflect.deleteProperty(target, property);
},
};
return new Proxy(obj, traps);
}