不说废话,直接上代码。。。。。。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="dv">
</div>
<script>
const obj = {
value: '你是'
}
// 监听者
class Watcher {
constructor(data, key, cal) {
this.data = data
this.key = key
this.cal = cal
Dep.target = this
data[key]
Dep.target = null
}
update() {
const value = this.data[this.key]
this.cal(value)
}
}
// 发布者
class Dep {
constructor(sub) {
this.subs = []
}
addSub(sub) {
if (sub && sub.update) {
this.subs.push(sub)
console.log(this.subs,'123')
}
}
// 发布通知
notify() {
this.subs.forEach(itemSub => {
itemSub.update()
})
}
}
const dep = new Dep()
// 数据劫持
Object.keys(obj).forEach(key => {
let value = obj[key]
Object.defineProperty(obj, key, {
get: function () {
console.log('get方法触发了---->>>>', value)
Dep.target && dep.addSub(Dep.target)
return value
},
set: function (newVal) {
console.log('set方法触发了---->>>>', newVal,Dep.subs)
value = newVal
dep.notify()
}
})
})
new Watcher(obj, 'value', (val) => {
document.getElementById('dv').innerHTML = val
})
// 初始化dom
function handleCick(obj) {
document.getElementById('dv').innerHTML = obj.value
}
handleCick(obj)
</script>
</body>
</html>