-1

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)
ThomasReggi
  • 42,912
  • 63
  • 199
  • 343

1 Answers1

2

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.

  • Can you convert an existing event to a Bacon bus? – ThomasReggi Apr 07 '15 at 23:47
  • You don't need to. If you want to emit events from Bacon API – forget about EventEmitter and use Bus.push to publish events to a bus. If you want to handle events from existing EventEmitter, you should use eventEmitter.emit(). I'll rewrite your example in my answer. – Max Philippov Apr 08 '15 at 00:09