计数器
再来看一个稍微复杂一点的例子,页面上有两个按钮,分别代表 +1 和 -1 操作,点击这两个按钮,将更新下方的计数结果:
按照流式设计的视角,我们要设计这几个流:
- +1 流:+1 流来自于 +1 按钮的点击事件
(+1) --- (+1) --- (+1) --- (+1)
- -1 流:-1 流来自于 -1 按钮的点击事件
(-1) --- (-1) --- (-1) --- (-1)
- 计数流:计数流首先合并自 +1 流和 -1 流,
(0) --- (-1) --- (+1) --- (+1) --- (+1) --- (-1)
然后进行累加操作:
(0) --- (-1) --- (0) --- (+1) --- (+2) --- (1)
通过 Cycle.js ,完成这个任务也不难:
const { div, button, p, makeDOMDriver } = CycleDOM;
function main(sources) {
const decrement$ = sources.DOM.select('#decrement').events('click').map(evt => -1);
const increment$ = sources.DOM.select('#increment').events('click').map(evt => +1);
const counter$ = Rx.Observable.of(0).merge(increment$).merge(decrement$).scan((prev, curr) => prev + curr);
return {
DOM: counter$.map(value =>
div([
button('#decrement', `-1`),
button('#increment', `+1`),
p(`${value}`)
]))
};
}
const drivers = {
DOM: makeDOMDriver('#app')
};
Cycle.run(main, drivers);