Skip to content

Instantly share code, notes, and snippets.

@pcornier
Last active August 23, 2017 07:40
Show Gist options
  • Save pcornier/ae2bc4f1285c5521e96c393131d8d3b6 to your computer and use it in GitHub Desktop.
Save pcornier/ae2bc4f1285c5521e96c393131d8d3b6 to your computer and use it in GitHub Desktop.
Poorman's reactive var in JS
// 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