Created
June 24, 2018 16:53
-
-
Save probil/700be7c74f9a7fc5ab575837c15cc458 to your computer and use it in GitHub Desktop.
Simple implementation of Vue reactivity system (computed properties)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import makeReactive from './makeReactive'; | |
let data = { | |
data: { | |
price: 5, | |
quantity: 2 | |
}, | |
computed: { | |
total() { | |
return this.price * this.quantity | |
}, | |
totalWithTax() { | |
return this.total * 0.2 + this.total; | |
} | |
}, | |
}; | |
makeReactive(data); | |
console.log('Total', data.total); | |
console.log('Total with tax', data.totalWithTax); | |
data.quantity = 1; | |
console.log('Total', data.total); | |
console.log('Total with tax', data.totalWithTax); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// === Expects vue-like object: | |
// { | |
// data: { | |
// <key>: <simple_value> | |
// }, | |
// computed: { | |
// <key>: <fn> | |
// }, | |
// } | |
export default obj => { | |
let target = null; | |
class Dep { | |
constructor() { | |
this.subscribers = [] | |
} | |
depend() { | |
if (target && !this.subscribers.includes(target)) { | |
this.subscribers.push(target) | |
} | |
} | |
notify() { | |
this.subscribers.forEach(sub => sub()) | |
} | |
} | |
Object.keys(obj.data).forEach(key => { | |
let internalValue = obj.data[key]; | |
const dep = new Dep(); | |
Object.defineProperty(obj, key, { | |
get() { | |
dep.depend(); | |
return internalValue | |
}, | |
set(newVal) { | |
internalValue = newVal; | |
dep.notify() | |
} | |
}); | |
}); | |
function watcher(myFunc) { | |
target = myFunc; | |
target(); | |
target = null | |
} | |
Object.keys(obj.computed).forEach(key => { | |
const fn = obj.computed[key].bind(obj); | |
let internalValue = fn(); | |
const dep = new Dep(); | |
Object.defineProperty(obj, key, { | |
get() { | |
dep.depend(); | |
return internalValue | |
}, | |
set(newVal) { | |
internalValue = newVal; | |
dep.notify(); | |
} | |
}); | |
watcher(() => { | |
obj[key] = fn(); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment