-
Notifications
You must be signed in to change notification settings - Fork 0
/
vue-DynamicDataBinding#01.js
51 lines (43 loc) · 1.39 KB
/
vue-DynamicDataBinding#01.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
/*
*动态数据绑定(一)
*http://ife.baidu.com/course/detail/id/15
*Run environment : Browser
*/
// ES5 Syntax
function Observer(obj){
//console.log("Observering..")
this.walk(obj)
}
var p = Observer.prototype
p.data = {}
p.walk = function(obj){
Object.keys(obj).forEach(function(key){
//console.log(key+": "+obj[key])
if(typeof obj[key] === "object"){return p.walk(obj[key])}
Object.defineProperty(p.data,key,{
get:function(){ console.log("You are visiting the attribute: "+ key+" - "+obj[key]); return obj[key] },
set:function(newValue) { console.log("You are updating the attribute: "+ key+" - "+ newValue); obj[key] = newValue }
})
})
}
// ES6 Syntax
Object.prototype.data = {};
class Observer{
constructor(obj){
//console.log("Observering..")
this.walk(obj)
}
walk(obj){
Object.keys(obj).forEach(key => {
//console.log(key+": "+obj[key])
if(typeof obj[key] === "object"){return Observer.prototype.walk(obj[key])}
Object.defineProperty(data,key,{
get:() => { console.log("You are visiting the attribute: "+ key+" - "+obj[key]); return obj[key] },
set:newValue => { console.log("You are updating the attribute: "+ key+" - "+ newValue); obj[key] = newValue }
})
})
}
}
/* Test Case */
var person1 = new Observer({name:"xiaoming", age:20, address:{add1:"China",add2:"UK"} });
person1.data.add1