node.js - Emit an event to a child object -


i'm writing nodejs module , trying bind event emitter "scrappy.get". seems can bind "scrappy" .... "scrappy.get(key).on('complete'...." not work.

how send event 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 me. thank you!

the problem this different because you're in different function. need instead capture scrappy instance's this variable , access instead:

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

also, instead of manually mutating prototype __proto__ , such, typically node core uses (and many module developers use) built-in util.inherits(). other things you're not returning instance get(). here's example 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; 

Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -