简体   繁体   English

使用Bacon.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. 我正在学习Bacon.js,我对应该如何发出事件感到非常困惑。

I have a super-simple example here of events in node.js 我这里有一个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. 我找不到一个示例,说明如何使用BaconJS和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)

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: 如果要使用NodeJS发射器,则代码如下所示:

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(). 请注意,尽管您必须将.onValue附加到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. 如果您对地图的工作方式有些困惑, BaconJS Snake示例可能会很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM