Skip to content

Instantly share code, notes, and snippets.

@dmikis
Created September 30, 2013 15:56
Show Gist options
  • Select an option

  • Save dmikis/6765930 to your computer and use it in GitHub Desktop.

Select an option

Save dmikis/6765930 to your computer and use it in GitHub Desktop.
Functional Reactive Programming (I hope...)
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input id="input1" type="range" min="0" max="100" value="50"></input>
<input id="input2" type="range" min="0" max="100" value="50"></input>
<div id="val"></div>
<script>
function ActiveValue(initValue) {
this._callbacks = [];
this._val = initValue;
}
ActiveValue.fromDOMInput = function (input) {
var value = new ActiveValue(input.value);
input.addEventListener('change', function (e) {
value.set(e.target.value);
});
return value;
};
ActiveValue.create = function (val) { return new ActiveValue(val); };
ActiveValue.prototype.set = function (value) {
this._val = value;
this._callbacks.forEach(function (callback) {
callback.fn.call(callback.ctx, value);
});
return this;
};
ActiveValue.prototype.get = function () {
return this._val;
};
ActiveValue.prototype.onValue = function (fn, ctx, doNotCallImmediatly) {
this._callbacks.push({fn: fn, ctx: ctx || window});
if (!doNotCallImmediatly) {
fn.call(ctx || window, this._val);
}
return this;
};
ActiveValue.prototype.dependsOn = function (fn) {
var deps = Array.prototype.slice.call(arguments, (typeof fn === 'function'));
var fn = typeof fn === 'function' ? fn : function (a) { return a; }
function onValue() {
this.set(fn.apply(window, deps.map(function (dep) { return dep.get(); })));
}
deps.forEach(function (dep) {
dep.onValue(onValue.bind(this));
}, this);
return this;
};
var val = ActiveValue.create()
.dependsOn(
function (i1, i2) {
return +i1 + +i2;
},
ActiveValue.fromDOMInput(document.querySelector('#input1')),
ActiveValue.fromDOMInput(document.querySelector('#input2'))
)
.onValue(function (v) {
document.querySelector('#val').innerHTML = v;
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment