Frage

I am using BaconJS to create two event streams likes this:

# Wait for start of the module
sStart = Bacon.fromCallback module.onStart.bind(module)
# Watch game ticks
sTick = Bacon.fromEventTarget emitter, 'tick'
# Combine it to do something
Bacon.onValues sStart, sTick, ->
    # Do something on each tick, but only when module has been started

I want to use it for synchronization. Once the module is started, it should start listening for ticks, not sooner. It almost works, but the callback is invoked for all past ticks that has been emitted before module start instead of just recent one. Than I want to that callback being invoked for each following tick.

I am pretty much starting with FRP, there is probably some elegant way how to deal with it, but I just don't see it for now. Any ideas ?

War es hilfreich?

Lösung 2

Looks like you're abusing Bacon.onValues, whose purpose is to create a new stream.

If you want to wait for the start of the module, just register the listener only when it has started:

sTick = Bacon.fromEventTarget emitter, 'tick'

module.onStart ->
  # when module has been started
  sTick.onValue ->
    # Do something on each tick

For a completely FRP-style, you would use flatMap:

sStart = Bacon.fromCallback module.onStart.bind(module)
# Watch game ticks
sTick = Bacon.fromEventTarget emitter, 'tick'
# Combine it to a new stream that is made from sTicks by each sStart event
sTicksAfterStart = sStart.flatMap -> sTick
sTickeafterStart.onValue ->
  # Do something on each tick

Andere Tipps

You can skip values using skipUntil like here.

startE = Bacon.fromCallback module.onStart.bind(module)
tickE = Bacon.fromEventTarget emitter, 'tick'
tickE.skipUntil(startE).onValue (tickValue) -> console.log tickValue

The flatMap solution above is valid too, but I find skipUntil easier to read.

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