我应该如何使用bacon.js保持几个值的运行总计? [英] how should I keep a running total of several values with bacon.js?

查看:270
本文介绍了我应该如何使用bacon.js保持几个值的运行总计?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 bacon.js 来处理。我想在一组文本输入中保持一个运行的值。 github网站上的例子使用 .scan 和一个加法器函数,它对该示例很好,因为它在流中使用-1和+1。但是我想要从流中删除值,如果他们被编辑,所以 .scan 解决方案将不会真正为我工作,或者我不是做正确。

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 fine for the example because it's using -1 and +1 in the stream. But I'd like values to be removed from the stream if they are edited, so the .scan solution won't really work for me or I'm not doing it right.

标记:

<ul style="repeat-direction: vertical; list-style-type: none;">
  <li><input data-group="0"></li>
  <li><input data-group="0"></li>
  <li><input data-group="0"></li>
</ul>
<ul style="repeat-direction: vertical; list-style-type: none;">
  <li><input data-group="1"></li>
  <li><input data-group="1"></li>
  <li><input data-group="1"></li>
</ul>

所以我有的解决方案是运行通过输入每当有一个throttled keyup事件,然后更新一个跨度,当它改变。

So the solution that I have is to run through the inputs whenever there's a throttled keyup event and then update a span when it changes.

groupZeroEvents = events.filter (val) ->
   Math.floor(val[0]) == 0 # the stream contains the group the input belongs to 

groupZeroEvents.onValue (val) ->
    sum = 0
    $("input[data-group='0']").each (i,el) ->
      sum += Math.floor($(el).val())
    $('span#sum-g0').html(sum)

它工作正常,但似乎跛脚 - 感觉像我缺少一种方法使用 Bacon.js 正确。

It works fine, but seems lame -- feels like I'm missing a way to use Bacon.js correctly.

推荐答案

总和取决于多个输入的当前值。如果你把这些输入建模为属性,你会得到一个更好的解决方案:

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

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

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

// sum Property
var groupZeroSum = Bacon.combineAsArray(groupZeroValues).map(sum)

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


$ b b

我没有时间来尝试这个,但这个想法一定会奏效。

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

这篇关于我应该如何使用bacon.js保持几个值的运行总计?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆