5
5

More than 5 years have passed since last update.

Kefir.jsで加算減算するStreamから値を得る

Posted at

いわゆる入門。

よくあるincイベントとdecイベントを合成させて現在の値を取るってやつ。

rpominov/kefir

ブラウザ立てるのめんどいので、coffeeでnode環境でイベントソースはEventEmitter。

Kefir = require 'kefir'
{EventEmitter} = require 'events'
emitter = new EventEmitter
inc = Kefir.fromEvents emitter, 'inc'
dec = Kefir.fromEvents emitter, 'dec'

Kefir.merge([
  inc.map(-> 1)
  dec.map(-> -1)
])
.scan ((acm, v) -> acm + v), 0
.onValue (i) -> console.log i

emitter.emit 'inc'
emitter.emit 'dec'
emitter.emit 'dec'
emitter.emit 'inc'
emitter.emit 'inc'
emitter.emit 'inc'

結果

0
1
0
-1
0
1
2

参考: Kefir.jsを使ってnehan.jsなビューアーをReactiveに作る - anti scroll

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5