Skip to content

Instantly share code, notes, and snippets.

@jiangkunhe

jiangkunhe/v1.js

Created Apr 10, 2019
Embed
What would you like to do?
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
You can’t perform that action at this time.