Skip to content Skip to sidebar Skip to footer

How Should I Keep A Running Total Of Several Values With Bacon.js?

Messing around with a bacon.js. I'd like to keep a running total of values in a group of text inputs. The example on the github site uses .scan and an adder function, which works f

Solution 1:

The sum depends on the current value of multiple inputs. If you model these inputs as Properties, you'll come to a nicer solution:

functionsum(xs) { return _.reduce(xs, (function(x,y) {return x + y}), 0); }

// array of Properties representing the value of each group-zero-elementvar groupZeroValues = $("input[data-group=0]").map(function(index, elem) {
     return $(elem).asEventStream("keyup")
            .map(function(e) { returnparseInt($(e.target).val()); })
            .toProperty(0)
     }).toArray();

// sum Propertyvar groupZeroSum = Bacon.combineAsArray(groupZeroValues).map(sum)

// assign Property value to the "text" method of the sum element
groupZeroSum.assign($("#sum-g0"), "text")

I didn't have time to actually try this, but the idea will definitely work.

Post a Comment for "How Should I Keep A Running Total Of Several Values With Bacon.js?"