响应式数据

很简朴的例子,基本描述了数据响应的原理。以下是研究过程代码。

class Publisher {
constructor() {
this.subscriber = []
}
subscribe(subFn) {
this.subscriber.push(subFn)
}
publish() {
this.subscriber.forEach(ob => ob.update())
}
}
class Observer {
constructor() {
this.value = ''
}
update() {
var html = ` <div> ${this.value} </div> `
document.body.innerHTML = html
}
}

class Reactive {
constructor() {
this.init()
}
init() {
var data = {
b: 2
}
this.obj = this.reactiveProxy(data)
this.mount()
}
reactiveProxy(data) {
let pub = new Publisher()
let ob = new Observer()
for (let p in data) {
let _p = data[p]
Object.defineProperty(data, p, {
get: function reactiveGetter() {
pub.subscribe(ob) // 订阅
return _p
},
set: function reactiveSetter(val) {
if (_p === val) return
ob.value = val
pub.publish() // 发布
_p = val
}
})
}
return data
}
$set(key, val) { // 测试改变属性b
this.obj[key] = val
}
mount() {
var html = ` <div> ${this.obj.b} </div> `
document.body.innerHTML = html
}

}


const r = new Reactive()
console.log(r)