Observer

观察者

  • 观察一个目标是否要做它自己的任务
  • 做这个目标任务相关联的任务

index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
;(()=>{
const target = new Target({
username:'CCCYYY',
password:'123456',
age:23,
gender:"male"
})

const init = ()=>{
console.log(target.username)
}
init()
})();

Observe.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
class Target {
constructor(data) {
this.data = data
this.observer = new Observer('#list')
this.init()
}

init() {
this.validateData(this.data)
this.proxyData()
}

validateData(data) {
const { username, password, age, gender } = data

username.length < 6 && (data.username = '')
password.length < 6 && (data.password = '')
typeof age !== 'number' && (data.age = 0)
!['male', 'female'].includes(gender) && (data.gender = 'male')
}

proxyData() {
const _this = this
for (let key in this.data) {
Object.defineProperty(this, key, {
get() {
this.observer.updateLog('get', key, _this.data[key])
return _this.data[key]
},
set(newValue) {
this.observer.updateLog('set', key, _this.data[key], newValue)
_this.data[key] = newValue
}
})
}
}
}

class Observer {
constructor(el) {
this.el = document.querySelector(el)
this.logPool = []
}

updateLog(type, key, oldValue, newValue) {
switch (type) {
case "get":
this.getProp(key, oldValue)
break;
case 'set':
this.setProp(key, oldValue, newValue)
break;
default:
break
}
}
getProp(key, value) {
const o = {
type: 'get',
dateTime: new Date(),
key,
value
}
this.logPool.push(o)
this.log(o)
}
setProp(key, oldValue, newValue) {
const o = {
type: 'set',
dateTime: new Date(),
key,
oldValue,
newValue
}
this.logPool.push(o)
this.log(o)
}

log(o) {
const { type, dateTime, key } = o
const oLi = document.createElement('li')
let htmlStr = ''

switch (type) {
case 'get':
htmlStr = `${dateTime}:
I got the key '${key}',
The value of the key is ${o.value}
`
break;
case 'set':
htmlStr = `${dateTime}:
I got the key '${key}',
The oldValue of the key is ${o.oldValue},
The newValue of the key is ${o.newValue},
`
break;
default:
break;
}
oLi.innerHTML = htmlStr
this.el.appendChild(oLi)
}
}