Formulas are the simplets way to describe dependency of one streams from others. Conjunctive operation in time could be simply implemented via streams formulas.
We have an markup:
<input type='text' id='a' value="0"> + <input type='text' id='b' value="0"> + <input type='text' id='c' value="0"> ) * <input type='text' id='d' value="0"> = <input type='text' id='result'>
This markup represents simple algebraic expression (a + b + c ) * d = X
, but all values changes over the time. We don't want to append to each input handler and observe changes of value and count final result. So we use Warden.Formula
// returns stream of given type from element #id
function from(id, type){
return $("#" + id).stream(type);
}
//return stream which contain integer type value from stream of given source
function value(src){
return from(src, 'keyup').map('@val()').map(parseInt);
}
//values of inputs
var a = value('a'),
b = value('b'),
c = value('c'),
d = value('d');
We prepared all streams, so let combine them with formula
var res = Warden.Formula([a,b,c,d], function(a,b,c,d){
// in this function a,b,c,d is a simple values of adequate streams
return (a + b + c) * d;
});
// now res is a stream which updates with given formula
// so we can bind res's value to the input with ID equals 'result'
res.bindTo($("#result"), 'val');
var color = value("color"),
shape = value("shape"),
size = value("size");
var figure = Warden.Formula([color,size,shape], function(color,size,shape){
return "Figure now is " + size + (shape.length ? " " : " and ") + color + " " + shape;
});
figure.bindTo($("#res"), 'html');