Last active
August 23, 2017 07:40
-
-
Save pcornier/ae2bc4f1285c5521e96c393131d8d3b6 to your computer and use it in GitHub Desktop.
Poorman's reactive var in JS
This file contains hidden or 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
// poorman's reactive var | |
function pmrv() { | |
this.value = null; | |
this.callers = {}; | |
this.set = function(v) { | |
this.value = v; | |
Object.keys(this.callers).forEach(k => this.callers[k]()); | |
} | |
this.get = function() { | |
this.callers[arguments.callee.caller] = arguments.callee.caller; | |
return this.value; | |
} | |
this.register = function(caller) { | |
this.callers[caller] = caller; | |
} | |
} | |
// tests: | |
test = new pmrv(); | |
test.set(5); | |
print = function() { | |
console.log('test: '+test.get()) | |
} | |
calc = function() { | |
let a = test.get() + 3 | |
console.log('add 3: ' + a); | |
} | |
explicit = function() { | |
console.log('triggered'); | |
} | |
print() | |
calc() | |
test.register(explicit); | |
test.set(2); | |
test.set(3); | |
test.set(4); | |
test.set(5); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment