原型处理程序不在自定义发射器上启动

时间:2014-01-27 20:31:35

标签: javascript node.js

在下面的代码中,我期望console.log输出与自定义发射器“输出”一起传递但未发生的数据。据我所知,Looper.prototype.output是通过使用服务器处理程序正确调用的,但它没有响应Looper.prototype.run中定义的发射器'output'事件。为什么我的输出事件处理程序不识别这些事件?

var express = require('express');
var http = require('http');
var spawn = require('child_process').spawn;
var util = require('util');
var fs = require('fs');
var EventEmitter = require("events").EventEmitter;
var sys = require("sys");

function Looper(req)  {
    this.req = req;
    EventEmitter.call(this);
}
sys.inherits(Looper, EventEmitter);

Looper.prototype.run = function() {
    var cmd = spawn('./flow',[this.req]); // <-- script that outputs req every second
    cmd.stdout.setEncoding('utf8');
    cmd.stdout.on('data', function(data) {
        this.emit('output',data);
    });
}

Looper.prototype.output = function(callback) {
    this.on('output', function(data) {
        return callback(data.trim());
    });
}

var looper = new Looper('blah');
looper.run();

var app       = express();
var webServer = http.createServer(app);

app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res) {
    res.send(
    "<h1>hello world</h1>"
    );

    looper.output(function(res) {
        console.log('blah');
        console.log(res);
    });
});
webServer.listen(3000);

1 个答案:

答案 0 :(得分:1)

Looper.prototype.run = function() {
    var cmd = spawn('./flow',[this.req]); // <-- script that outputs req every second
    cmd.stdout.setEncoding('utf8');
    cmd.stdout.on('data', function(data) {
        this.emit('output',data);
    //  ^ not what you think it is.
    });
}

我认为this不是你认为的那种回调。您需要首先捕获回调之外的值。

Looper.prototype.run = function() {
    var self = this; // save this
    var cmd = spawn('./flow',[this.req]); // <-- script that outputs req every second
    cmd.stdout.setEncoding('utf8');
    cmd.stdout.on('data', function(data) {
        self.emit('output',data); // use previously saved value of this
    });
}

否则,this将默认为全局对象,当全局对象发出事件时,没有人正在侦听它。