2012-04-22 94 views
5

我做了本教程node.js eventEmitter,它工作得很好。我添加了一個使用http.request獲取數據的方法,該方法工作併發送數據。node.js eventEmitter + http.request

問題在於聽衆沒有捕捉到事件!

有人可以幫忙嗎?

代碼:

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 

回答

1

一個硬斑...

的問題是從this.emit("tweets", tweets);this指針。您正在通過傳遞給response.on的匿名回調進行此調用,因此this不代表您創建的Eventer對象。 爲了解決這個問題,你需要「保存」指針(一種常見的做法)this

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

這就是它,謝謝:) – 2012-04-22 20:45:40

相關問題