【问题标题】:node.js eventEmitter + http.requestnode.js eventEmitter + http.request
【发布时间】:2012-05-03 12:30:21
【问题描述】:

我做了这个教程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

【问题讨论】:

    标签: node.js eventemitter


    【解决方案1】:

    很难发现...

    问题是来自this.emit("tweets", tweets);this 指针。您在传递给response.on 的匿名回调中执行此调用,因此this 不代表您创建的Eventer 对象。 要解决它,您需要“保存”this 指针(一种常见做法)。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-19
      • 2015-08-18
      • 1970-01-01
      • 2012-12-17
      • 2012-03-09
      • 2012-07-24
      • 1970-01-01
      相关资源
      最近更新 更多