0

使用 cycle.js 和 xstream,我想计算按钮点击次数并重置它们。

我打算通过在最后一次重置后计算所有按钮点击来实现这一点。为此,我想放弃所有按钮点击,直到最后一次重置,并计算剩下的内容。

但是我留下了 2 个不起作用的按钮

有什么建议吗?

function main(sources: ISources): ISinks {
  const dom = sources.dom;
  const resetClick$ = dom.select("#resetButton")
    .events("click")
    .map(ev => 0)
    .startWith(0)

  const button1Click$ = dom.select("#button1")
    .events("click")
    .compose(dropUntil(resetClick$.last()))
    .map(ev => 1)
    .fold((acc, n) => acc + n, 0)
    .startWith(0)

  const button2Click$ = dom.select("#button2")
    .events("click")
    .compose(dropUntil(resetClick$.last()))
    .map(ev => 1)
    .fold((acc, n) => acc + n, 0)
    .startWith(0)

  const vtree$ = Stream.combine(button1Click$, button2Click$)
    .map(n =>
      div([
        input("#button1", { attrs: { type: "button", value: "Click Me!"}}),
        input("#button2", { attrs: { type: "button", value: "Click Me!"}}),
        input("#resetButton", { attrs: { type: "button", value: "Reset!"}}),
        p(["Clicks: " + n[0] + " + " + n[1]]),
        p(["Click total: " + (n[0] + n[1])])
      ])
    )

  const sinks: ISinks = {
    dom: vtree$
  };
  return sinks;
}
4

1 回答 1

1
const resetClick$ = dom.select("#resetButton")
  .events("click")
  .map(ev => 0)

const button1Click$ = dom.select("#button2")
    .events("click")
    .map(ev => 1)

const button1WithReset$ = Stream.merge(button1Click, resetClick$)
  .fold((acc, n) => { 
      if (n == 0) return 0
      else return acc + n
  }, 0)

这应该可以解决问题。然后,您可以对button2Click.

通过合并button1click$resetClick$我们得到一个流,它要么发出0要么1. 并且使用 fold,我们可以在每次合并流发出时重置计数器0

于 2016-09-19T10:02:25.783 回答