Re: Store callbacks for signals in a C++ addon

434 views
Skip to first unread message

mscdex

unread,
Oct 2, 2012, 6:42:32 PM10/2/12
to nodejs
On Oct 2, 5:28 pm, Alexandre Quessy <que...@gmail.com> wrote:
> I need to be able to publish events from my C++ addon. This way, users of
> my nodejs addon will be notified in their JavaScript server-side script
> when they occur.

Why not emit events instead?

Ben Noordhuis

unread,
Oct 2, 2012, 6:42:45 PM10/2/12
to nod...@googlegroups.com
On Tue, Oct 2, 2012 at 11:28 PM, Alexandre Quessy <que...@gmail.com> wrote:
> Hello everyone,
>
> I need to be able to publish events from my C++ addon. This way, users of my
> nodejs addon will be notified in their JavaScript server-side script when
> they occur.
>
> So, I guess I want to store all the javascript callbacks that are registered
> in a global map in my C++ addon. (of a member of an object)
> Should I store them as a std::map<v8::Local<v8::Function> > ? What the right
> scope to use?

It's idiomatic to push as much as possible to JS land. Here is a
minimal C++ event emitter and a JS shim that does the actual
dispatching. Dispatching is left as exercise to the reader. :-)

// in Init()
Persistent<Object> context_obj = Persistent<Object>::New(Object::New());
target->Set(String::New("context"), context_obj);

// elsewhere in your code
Local<Value> args[] = { String::New("ping") };
node::MakeCallback(context_obj, "on", ARRAY_SIZE(args), args);

And the JS shim:

var bindings = require('./bindings'); // the .node file
bindings.context.on = function(name) {
console.log(name); // prints "ping"
// now invoke the user's callbacks
};

Hope that helps.
Reply all
Reply to author
Forward
0 new messages