Last active
February 13, 2021 17:57
-
-
Save belozerskiy/e46f2ae36c5204708dca99afbacca7bb to your computer and use it in GitHub Desktop.
Very simple dependency tracker system like in vue.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
function Dependency(name, value, cb = null) { | |
this.name = name | |
this.value = value | |
this.callback = cb | |
} | |
function DependencyTracker() { | |
this._stack = []; | |
this.add = function(dep) { | |
this._stack.push(dep); | |
return () => this.remove(dep) | |
} | |
this.remove = function(dep) { | |
this._stack = this._stack.filter((d) => d != dep) | |
} | |
this.notify = function(dep) { | |
this._stack | |
.filter((d) => d.name == dep.name) | |
.forEach((d) => d.callback()) | |
} | |
} | |
const tracker = new DependencyTracker(); | |
function createWatcher(name, value) { | |
const context = { | |
name, | |
value, | |
} | |
let _dep | |
function fn(cb){ | |
_dep = new Dependency(name, value, cb) | |
return tracker.add(_dep) | |
} | |
Object.defineProperty((window || global || this_), context.name, { | |
get() { | |
return context.value; | |
}, | |
set(value) { | |
context.value = value; | |
tracker.notify(_dep); | |
} | |
}); | |
return fn | |
} | |
const watch = createWatcher('x', 10) | |
const unwatch = watch(function() { | |
console.log('watcher') | |
}) | |
const unwatch2 = watch(function() { | |
console.log('watcher 2') | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment