On Jan 20, 2:20 am, Peter Braden <
peterbrad...@gmail.com> wrote:
> Is there a way to put EventEmitter at the top of the chain in c++ land?
No, C++ EventEmitter was removed early on in node v0.5.x.
Here's the workaround:
Step 1: Add #include <node_object_wrap.h> and static
Persistent<String> emit_symbol; to the top of your cpp file, above the
class declaration
Step 2: Have your addon's class inherit from ObjectWrap
Step 3: Emit events like so (you may wish to wrap this code into its
own C++ function for easier readability):
// emits 'myEventName' with an integer argument of 100 where
emit_symbol is
Local<Value> emitArgs[2];
emitArgs[0] = String::New("myEventName");
emitArgs[1] = Integer::New(100);
Local<Value> emit_v = handle_->Get(emit_symbol);
Local<Function> emit = Local<Function>::Cast(emit_v);
TryCatch tc;
emit->Call(handle_, 2, emitArgs);
if (tc.HasCaught()) {
// propagate error
}
Step 4: Create a node js module that sets the __proto__ of your
addon's prototype to that of EventEmitter's prototype, like so:
// mymodule.js
var EventEmitter = require('events').EventEmitter,
addon = require('./path/to/compiled/cpp/addon');
addon.prototype.__proto__ = EventEmitter.prototype;
module.exports = addon;
Step 5: Just require('./mymodule') and use it as if you were
require()'ing your addon directly
Step 6: ???
Step 7: Profit!