Wednesday, 15 April 2015

javascript - Callback function in Node.js addon -



javascript - Callback function in Node.js addon -

i wrapping can bus manager api in node.js extension. works well, final result:

// list interfaces var interfaces = addon.listdevices(); console.log(interfaces); // allocating new port var port = new addon.canport(); port.setcallback(function(msg) { // receive can datagrams console.log(msg); }); // connect 1st port port.connect(0); // send datagram port.sendstruct(127508, 6, array(0, 70, 5, 50, 0, 131, 114, 0));

every function ok setcallback function. actually, don't know do. have c++ callback of this type :

void canport::setreceivecallback(functioncallback func);

which phone call function when receives new datagram.

i found in http://nikhilm.github.io/uvbook/threads.html help, can't find right way same lastly example. know should utilize uv, don't know how...

moreover, i'm using v0.11.14-pre of node.js, lot of documentation out of date...

thanks, nicolas.

although kind of old, used hybrid javascript/c++ mechanism integrate external callbacks. phone call uv_queue_work() in callback uv_work_t performs nothing, , utilize after_work_cb phone call javascript function:

// c++ void nop() {} void jscallback(uv_work_t* handle, int status) { // extract some_data handle , phone call node::makecallback() here // create phone call emit('event', some_data); delete handle; } void called_by_third_party_callback(some_type some_data) { uv_work_t uv = new uv_work_t(); if (!uv) { // error } // ensure some_data accessible via uv->data if (uv_queue_work(uv_default_loop(), uv, nop, jscallback) != 0) { delete uv; } }

on javascript side used string-to-function map implement simple event emitter mechanism on top of engine object:

// javascript exports.engine.prototype.eventmap = []; exports.engine.prototype.on = function (name, func) { if (typeof (func) === "function") { this.eventmap[name] = func; } exports.engine.prototype.emit = function (name, value) { var func = this.eventmap[name]; if (typeof (func) === "function") { func(value); } }

this how utilize it:

// javascript var obj = new require('myaddon').engine(); obj.on('event', function (v) { console.log('event: ' + v); });

sorry using comments excessively. code intertwined shown snipplets.

javascript c++ node.js add-on

No comments:

Post a Comment