EventEmitter coming with node.js is handy most of the time, and I implement this useful utility in C++ after finishing writing Functor. Yes, we need Functor to make it much more easier to write this fabulous utility. (Why don't you use lamdba? I'll talk about that later in this post)
It's extremely simple to use EventEmitter in node.js
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', () => {
console.log('an event occurred!');
});
myEmitter.emit('event');
——https://nodejs.org/api/events.html
And the C++ version of EventEmitter need to be as easy as it is in node.js. As a matter of fact, this class made it.
#include <iostream>
#include <sstream>
#include <thread>
#include <vector>
#include "EventEmitter.hpp"
using namespace std;
class emitter : public EventEmitter {
};
int main(int argc, const char * argv[]) {
emitter emitter;
emitter.on("event", [&emitter](int data) {
ostringstream osstream;
osstream << "data: " << data << '\n';
std::cout << osstream.str();
});
vector<thread> threads;
for (int i = 0; i < 10; i++) {
threads.emplace_back([&emitter, i]() {
emitter.emit("event", i);
});
}
for (auto &t : threads) t.join();
}
Continue reading A simple EventEmitter in C++ →