function Reactive(data) {
for(let k in data) {
let dep = new Dep()
let oldVal = data[k]
Object.defineProperty(data, k, {
configurable: true,
enumerable: true,
get: function() {
Dep.target ? dep.add() : undefined
return oldVal
},
set: function(val) {
oldVal = val
dep.notify(val)
}
})
}
}
function Dep() {
this.deps = []
this.add = function() {
this.deps.push(Dep.target)
}
this.notify = function(...args) {
this.deps.forEach(watcher => watcher.effect(args))
}
}
Dep.target = null
function Watcher(getter, effect) {
this.effect = effect
Dep.target = this
getter()
Dep.target = null
}
let obj = {name: `nowll`, age: 27}
Reactive(obj)
new Watcher(() => obj.name, (newVal) => {
console.log(`effect works!, newVal = ${newVal}`)
})
new Watcher(() => obj.name, (newVal) => {
console.log(`this is another name effect`)
})
new Watcher(() => obj.age, (newVal) => {
console.log('this is age effect')
})
obj.name = 'Yang'
obj.age = 26
console