2012-04-22 11 views
5

hice este tutorial node.js eventEmitter, funcionó muy bien. Agregué un método que usa http.request para obtener datos, que funciona y emite los datos.node.js eventEmitter + http.request

¡El problema es que el oyente no capta el evento!

¿Alguien puede ayudar?

código:

var events = require('events'); 
var util = require('util'); 
var http = require('http'); 

//http request options, it query the twitter api and get the public timeline, works! 
var options = { 
    hostname : 'api.twitter.com', 
    port : 80, 
    method : 'get', 
    path : '/1/statuses/public_timeline.json?count=3&include_entities=true' 
} 

// The Thing That Emits Event 
Eventer = function(){ 
    events.EventEmitter.call(this); 

//tutorial examples 
    this.kapow = function(){ 
    var data = "BATMAN" 
    this.emit('blamo', data); 
    } 

//tutorial examples 
    this.bam = function(){ 
    this.emit("boom"); 
    } 

//my method 
    this.GetTweetList = function(){ 
    var tweets = ""; 
     var req = http.request(options, function(response){ 
        var body = ""; 
        response.on('data',function(data){ 
         body += data; 
        }); 
        response.on('end', function(){ 
         tweets = JSON.parse(body); 
         this.emit("tweets", tweets); 
         util.puts('!!!!!!!!!! got some data !!!!!!!!!! \n'); 
        }); 
       }); 
     req.end(); 
    } 
}; 
util.inherits(Eventer, events.EventEmitter); 

// The thing that listens to, and handles, those events 
Listener = function(){ 

//tutorial examples 
this.blamoHandler = function(data){ 
    console.log("** blamo event handled"); 
    console.log(data); 
    }, 

//tutorial examples 
    this.boomHandler = function(data){ 
    console.log("** boom event handled"); 
    } 

//my listener method 
    this.GetTweetListHandler = function(data){ 
     console.log("** tweets event handled"); 
     util.put(data); 
     util.puts('!!!!!!!!!! got some data in listener !!!!!!!!!! \n'); 

    } 

}; 

// The thing that drives the two. 
//instanciating the object and liking the methodes 
var eventer = new Eventer(); 
var listener = new Listener(eventer); 
eventer.on('blamo', listener.blamoHandler); 
eventer.on('boom', listener.boomHandler); 
eventer.on('tweets', listener.GetTweetListHandler); 


//calling the methodes 
eventer.kapow();//works 
eventer.bam();//works 
setInterval(eventer.GetTweetList, 2000); 
//eventer.GetTweetList();// still waiting but the eventer display that he got the data 

Respuesta

1

uno difícil de detectar ...

El problema es la this puntero desde this.emit("tweets", tweets);. Está realizando esta llamada desde una devolución de llamada anónima pasada al response.on, por lo que this no representa el objeto Eventer que ha creado. Para resolverlo, debe "guardar" el puntero this (una práctica común).

var tweets = ""; 
var self = this; 
.... 
self.emit("tweets", tweets); 
+0

inded that was it, thanks :) –

Cuestiones relacionadas