NodeJS:对象原型事件处理

时间:2013-12-25 22:52:28

标签: node.js events object prototype

我有以下代码......

Lib.js

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

app = module.exports =  function(){
    var name = "TestAPP";
    events.EventEmitter.call( this );
};
util.inherits(app,events.EventEmitter);


app.prototype.createServer = function(){
    net.createServer({allowHalfOpen:false}, this.listening).listen(8000);
    // I've also tried
    // net.createServer({allowHalfOpen:false}, app.prototype.listening).listen(8000);
}

app.prototype.listening = function(){
    util.log(this.name + ' > Server is listening.');
}

Test.js

var app = require('./lib');
var a = new app();
a.createServer();

但是当我运行它时,服务器正在侦听,但是侦听事件不会触发。

我不知道我是否遗漏了一些微不足道的东西。任何帮助将不胜感激。

感谢。

1 个答案:

答案 0 :(得分:0)

你错误的'连接'监听器用于'监听'监听器。查看this链接。

app = module.exports =  function(){
    this.name = "TestAPP";
    events.EventEmitter.call( this );
};
util.inherits(app,events.EventEmitter);

app.prototype.createServer = function(){
    net.createServer({allowHalfOpen:false}).listen(8000, this.listening(this));
}

app.prototype.listening = function(a){
    util.log(a.name + ' > Server is listening.');
}