Skip to content

Instantly share code, notes, and snippets.

@holocc
Created April 10, 2019 15:08
Show Gist options
  • Save holocc/8d35bff75605576ff03107e0eb969975 to your computer and use it in GitHub Desktop.
Save holocc/8d35bff75605576ff03107e0eb969975 to your computer and use it in GitHub Desktop.
vue observe demo
const data = {}
let a = 1
let dep = []
let Target = null
Object.defineProperty(data, 'a', {
set: function(val) {
a = val
dep.forEach(fn => fn())
},
get: function() {
if (Target) {
dep.push(Target)
Target = null
}
return a
}
})
function watch(key, fn) {
Target = fn
data[key]
}
watch('a', function() {
console.log(1)
})
watch('a', function() {
console.log(2)
})
data.a = 3
console.log(data.a)
var data = {
a: 1,
b: 2
}
let Target = null
function observe(obj) {
const keys = Object.keys(obj)
for (let i = 0; i < keys.length; ++i) {
const dep = [], key = keys[i]
let cacheVal = obj[key]
Object.defineProperty(obj, key, {
get: function() {
if (Target) {
dep.push(Target)
Target = null
}
return cacheVal
},
set: function(newVal) {
dep.forEach(fn => fn())
cacheVal = newVal
}
})
}
}
observe(data)
function watch(key, fn) {
Target = fn
data[key]
}
watch('a', function() {
console.log('a: 1')
})
watch('a', function() {
console.log('a: 2')
})
watch('b', function() {
console.log('b: 1')
})
watch('b', function() {
console.log('b: 2')
})
data.a = 3
data.b = 10
console.log(data.a)
console.log(data.b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment