- Mastering Reactive JavaScript
- Erich de Souza Oliveira
- 214字
- 2021-07-09 20:33:07
Observable node event emitter (fromEvent)
Lots of Node.js modules implement an event emitter, which is basically an object with the on() method that is called every time an event happens. We can transform these objects into EventStreams of bacon.js to take advantage of all the transformations. The method fromEvent() has the following signature:
Bacon
.fromEvent(eventEmitter,eventName);
The parameters are eventEmitter; the node eventEmitter object; and eventName, the name of the event. We can use the fs module to show the usage of this method.
To read a file using the fs node module that uses an event emitter, we need to create a readStream for the file using the following code:
var fs = require('fs');
var FILE_PATH = 'SOME FILE';
var readStream = fs.createReadStream(FILE_PATH,'utf8');
Then, subscribe to the events on this emitter using the on() method, as follows:
readStream.on('data',(content)=>console.log(content));
To transform this code into a code using a bacon.js EventStream, we need to change the last line of the following code:
var eventStream = Bacon.fromEvent(readStream,'data');
eventStream
.onValue((content)=> console.log(content));
So comparing with the method signature, our eventEmitter parameter is the readStream object and eventName is data.
The fromEvent() method can also be used to listen to DOM events (similar to the asEventStream() method), as you can see in the following code:
var clickEventStream = Bacon.fromEvent(document.getElementById('#myButton'), 'click');
- Linux網絡管理與配置(第2版)
- Windows Server 2012 Hyper-V:Deploying the Hyper-V Enterprise Server Virtualization Platform
- 精通Linux內核開發
- SharePoint 2013 WCM Advanced Cookbook
- Linux集群和自動化運維
- Linux運維最佳實踐
- 操作系統分析
- 分布式系統設計實踐
- Windows 7實戰從入門到精通(超值版)
- OpenStack Essentials(Second Edition)
- VMware vSphere 5.1 Cookbook
- Java EE 8 High Performance
- 大規模Linux集群架構最佳實踐:如何管理上千臺服務器
- Administering ArcGIS for Server
- OpenStack Trove Essentials