events - How do I emit to an eventListener from inside a nested function in Node.js (javascript scoping issue) -


i writing code below parses sites api 1 @ time, tells event queue ready next object parse. having issues since still new javascript scoping, , emit siteparser or call emitfornext function. cannot seem bring emitfornext scope in error callback.

   function siteparser(){         this.emitfornext = function  (message) {             this.emit("next", message);         };          this.pulljson = function (path, processjson) { //processjson callback function                 var options = {                 host: 'www.site.com',                 port: 80,                 path: path             }              //console.log("... processing "+path);               //pulls entire json request via chunks             http.get(options, function  (res) {                 var resjson = ''; //stores comment json stream given in res                 res.on('data',  function (chunk) {                     resjson+=chunk;                    });                   res.on('end', function () {                     var objson = (json.parse(resjson));                        if (objson.hasownproperty("error")){                          console.log(objson);                         console.log('... ', path, ' not exist');                         //                         //need next event emmiter here need figure out scope                         //                         //                        } else {                         processjson(objson); //call callback function                     }                 }) ;             }).on('error', function  (e) {                 emitfornext("got error: " + e.message);             });         };     } 

javascript has function scoping, if declare variable var keyword, local current function. when access variable, scope chain consist of current function, it's parent function, …. try:

function one() {     var foo = 'foo';      function two() {         console.log(foo) // undefined. i'll explain         var foo = 'bar';         console.log(foo) // bar     }      two()     console.log(foo) // foo } one() 

most of time define variables @ beginning of functions, because variable defined in function's body hoisted. basically, means it's available in whole function, before it's defined in case it's value undefined.

for example if variable not defined referenceerror, in snippet below, both console.log() print undefined.

function foo() {      console.log(bar);      if (0) {          var bar = 'bar';      }      console.log(bar); } 

so, common practice that, when write long functions, map self.

function siteparser() {     var self = this;     // ...     .error('error', function(err) {         self.emitfornext("got " + err.message);     }) } 

you should not write methods in constructor, it's usefull when want privacy, in case you'd better use prototypes.

putting together, write:

var siteparser = function() {};  siteparser.prototype.emitfornext = function(message) {     this.emit("next", message); };  siteparser.prototype.pulljson = function(path, processjson) {      var self    = this,         options = {             host: 'www.site.com',             port: 80,             path: path         };      http.get(options, function(res) {         // ...     }).on('error', function  (e) {         self.emitfornext("got error: " + e.message);     }); }; 

Comments

Popular posts from this blog

jasper reports - Fixed header in Excel using JasperReports -

media player - Android: mediaplayer went away with unhandled events -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -