Search code examples
javascriptnode.jseventsfrpbacon.js

Emitting events with Bacon.js


I'm learning Bacon.js and I'm very confused as to how I'm supposed to emit events.

I have a super-simple example here of events in node.js

var events = require('events')
var eventEmitter = new events.EventEmitter()

eventEmitter.on("add", function(data){
  console.log(data+1)
  return data+1
})

eventEmitter.emit('add', 5)
eventEmitter.emit('add', 3)

setTimeout(function(){
  eventEmitter.emit('add', 13)
}, 1000)

setTimeout(function(){
  eventEmitter.emit('add', 10)
}, 3000)

I can't find one example of how something simple like this would be done with BaconJS and node.

I tried this:

var add = Bacon.fromEvent(eventEmitter, "add")

add.onValue(function(data){
  return data+1
})

add.map(5)
add.map(3)
add.map(13)
add.map(10)

Solution

  • You need Bacon Bus. Instead of emitting an event, you just push data to a Bus.

    If you want to use NodeJS emitter, here how your code might look like:

    var add = Bacon.fromEvent(eventEmitter, "add")
    
    // every time we get an event we add 1 to its' value
    add.map(function(data){
      return data+1
    }).onValue(function(data){
      console.log(data)
    })
    eventEmitter.emit('add',10)
    

    Note though that you must append .onValue to the result of add.map(). Otherwise console will output only the original values from your event stream. map creates a new, modified stream.

    BaconJS Snake example might be useful if you feel a bit confused on how map works.