Frage

So I'm fairly new to the functional programming paradigm and especially new to Bacon.js and FRP. I need some advice on how to conceptualize control flow in FRP. I have a timer in an event stream that counts down to zero. When it has reached zero I want to hide the HTML timer counter and stop the event stream.

timer.coffee

# decrement function
dec = (x,y) ->
    x-y

# Create a timer counting down from 100 every 10th millisecond
timer = Bacon.interval(10, 1).scan(100, dec)

timer.onValue (e) ->
  # output the current timer value to the DOM
  $("#timer").text(e)

  # if the timer has reached 0, hide the DOM object 
  $("#timer").hide() if e is 0

timer.html

<body>
  <div id="timer"></div>
</body>

Should I really use if/else to check a value and call a function as I'm doing in onValue()? Somehow it feels as if I'm doing it wrong. And when I'm satisfied with the eventStream how do I stop/close it?

War es hilfreich?

Lösung

When defining your stream, include takeWhile to end the stream on a condition. You can use onEnd to assign a side effect on stream end.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top