EventEmitter, emit from listener function

38 views
Skip to first unread message

Krzysztof Rosiński

unread,
Mar 20, 2015, 10:50:14 AM3/20/15
to nod...@googlegroups.com
Hi,

I'm trying to emit event from serial port 'on data' function but the event doesn't pass through to my implmentation. When I directly call parse function event is emitted correctly. Can you please advice what I'm doing wrong here? Here is my code:

function GPS(device, baudrate) {
    events
.EventEmitter.call(this);
   
   
this.port = new serialport.SerialPort(this.device, {
        baudrate
: this.baudrate,
        parser
: serialport.parsers.readline('\r\n')
   
});
   
   
this.port.on('data', this.parse);
}

util
.inherits(GPS, events.EventEmitter);

GPS
.prototype.parse = function(line) {

   
(...)
   
this.emit('data', data)
};

module.exports = GPS;

// Implementation
var gps = new GPS('/dev/ttyACM0', 115200);

gps
.on("data", function(data) {
   
// Handle data
});


Ryan Graham

unread,
Mar 22, 2015, 5:38:22 PM3/22/15
to nod...@googlegroups.com

If I recall correctly, event emitters call event handlers with `this` bound to the event emitter itself. That means that your parse function is being called with `this` bound to the port that is emitting the event, not the GPS instance you got it from.

~Ryan


--
Job board: http://jobs.nodejs.org/
New group rules: https://gist.github.com/othiym23/9886289#file-moderation-policy-md
Old group rules: https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
---
You received this message because you are subscribed to the Google Groups "nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nodejs+un...@googlegroups.com.
To post to this group, send email to nod...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/nodejs/50d706ad-8582-4bfa-a711-51bb050c1a18%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages