How to inherit from EventEmitter in Native Objects

938 views
Skip to first unread message

Peter Braden

unread,
Jan 20, 2012, 2:20:49 AM1/20/12
to nod...@googlegroups.com
Hi,

I'm writing a c++ extension and I want my object to be able to act as a Stream. That means that I have to have EventEmitter somewhere on the prototype chain. But the object is native, and it's already inheriting from another native object with  :

     constructor->Inherit(Parent::constructor);

Is there a way to put EventEmitter at the top of the chain in c++ land?

(My code is https://github.com/peterbraden/node-opencv and the inheritance chain is Image->Matrix)

Thanks

P

mscdex

unread,
Jan 20, 2012, 3:07:23 AM1/20/12
to nodejs
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!

Ben Noordhuis

unread,
Jan 20, 2012, 8:29:23 AM1/20/12
to nod...@googlegroups.com
On Fri, Jan 20, 2012 at 08:20, Peter Braden <peterb...@gmail.com> wrote:
> Hi,
>
> I'm writing a c++ extension and I want my object to be able to act as a
> Stream. That means that I have to have EventEmitter somewhere on the
> prototype chain. But the object is native, and it's already inheriting from
> another native object with  :
>
>      constructor->Inherit(Parent::constructor);
>
> Is there a way to put EventEmitter at the top of the chain in c++ land?

Have a look here: https://github.com/bnoordhuis/node-event-emitter

Reply all
Reply to author
Forward
0 new messages