-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatch.js
65 lines (64 loc) · 1.65 KB
/
watch.js
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
Object.defineProperty(Object.prototype, 'watch', {
configurable: true,
enumerable: false,
writable: false,
value: function(handler, props){
let propertiesToWatch = [];
if(props){
if(props.constructor === Array || props.constructor === String)
propertiesToWatch = propertiesToWatch.concat(props);
else{
console.log("properties must be String or Array");
return false;
}
}
propertiesToWatch = propertiesToWatch.length ? propertiesToWatch : Object.keys(this);
let applyHandler = (prop, toApply) => {
toApply = toApply || this;
let oldVal = this[prop];
let newVal = oldVal;
let get = function(){
return newVal;
}
let set = function(val){
oldVal = newVal;
newVal = val;
handler.call(this, newVal, oldVal, prop);
return newVal;
}
delete this[prop];
Object.defineProperty(this, prop, {
configurable: true,
enumerable: true,
get: get,
set: set
});
}
propertiesToWatch.forEach(applyHandler);
}
});
Object.defineProperty(Object.prototype, "unwatch", {
writable: false,
value: function(props){
let propertiesToUnWatch = [];
if(props){
if(props.constructor === Array || props.constructor === String)
propertiesToUnWatch = propertiesToUnWatch.concat(props);
else{
console.log("properties must be String or Array");
return false;
}
}
propertiesToUnWatch = propertiesToUnWatch.length ? propertiesToUnWatch : Object.keys(this);
let removeWatch = (prop) => {
let val = this[prop];
Object.defineProperty(this, prop, {
get: undefined,
set: undefined
});
delete this[prop];
this[prop] = val;
}
propertiesToUnWatch.forEach(removeWatch);
}
});