0

I'm writing a nodejs module and trying bind an event emitter to "scrappy.get". It seems that I can only bind it to "scrappy" .... so "scrappy.get(key).on('complete'...." does not work.

How do I send the event to the child object 'get'?

My NodeJS module:

     var util = require('util'),
    EventEmitter = require('events').EventEmitter;

function Scrappy(id) {
}

util.inherits(Scrappy, EventEmitter);

Scrappy.prototype.get = function (key) {
  var self = this;
  self.emit('complete', "here");
  **return this;**
}

module.exports = Scrappy;

My NodeJS app code:

var Scrappy = require('./scrappy.js')
var scrappy = new Scrappy("1234");

scrappy.get("name").on('complete', function(data){
    console.log("secondary");
});

Result:

scrappy.get("name").on('complete', function(data){
                    ^
TypeError: Cannot call method 'on' of undefined

Edit: Solved. Adding "return this;" solved it for me. Thank you!

klinquist
  • 246
  • 1
  • 4
  • 15

1 Answers1

1

The problem is that your this is different because you're in a different function. You need to instead capture the Scrappy instance's this to a variable and access that instead:

Scrappy.prototype.get = function (key) {
  var self = this;
  redisclient.get(key, function(err, reply) {
    self.emit('complete', reply);
  });
};

Also, instead of manually mutating the prototype with __proto__ and such, typically what node core uses (and what many module developers use) is the built-in util.inherits(). The other things is that you're not returning the instance from get(). Here's an example with these changes:

var util = require('util'),
    EventEmitter = require('events').EventEmitter;

function Scrappy(id) {
}
util.inherits(Scrappy, EventEmitter);

Scrappy.prototype.sendToEngine = function(message) {

};
Scrappy.prototype.set = function(key, value) {

};
Scrappy.prototype.get = function(key) {
  var self = this;

  redisclient.get(key, function(err, reply) {
    self.emit('complete', reply);
  });

  return this;
};

module.exports = Scrappy;
mscdex
  • 104,356
  • 15
  • 192
  • 153
  • Hm, doesn't seem to be working. In the nodejs app, I'm still getting: scrappy.get("name").on('complete', function(data){ ^ TypeError: Cannot read property 'on' of undefined – klinquist Dec 05 '14 at 21:37
  • The main problem is that you're not returning the Scrappy instance from `get()` to be able to call `.on()`. – mscdex Dec 05 '14 at 21:50
  • mscdex, thank you for your assistance, but it isn't working for me. – klinquist Dec 05 '14 at 21:52
  • I've updated my question to simplify the code as much as I can - still getting the same problem. – klinquist Dec 05 '14 at 21:56