Created
August 1, 2018 07:18
-
-
Save ilya-korotya/74ea761222825c930293d7f2dfaccc71 to your computer and use it in GitHub Desktop.
Reactive with vanilla JS
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
let data = { price: 5, quantity: 2 } | |
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(data).forEach(key => { | |
let internalValue = data[key] | |
const dep = new Dep() | |
Object.defineProperty(data, key, { | |
get() { | |
dep.depend() | |
return internalValue | |
}, | |
set(newVal) { | |
internalValue = newVal | |
dep.notify() | |
} | |
}) | |
}) | |
function watcher(myFunc){ | |
target = myFunc | |
target() | |
target = null | |
} | |
watcher(() => { | |
data.total = data.price * data.quantity | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment