【问题标题】:NodeJS : Object Prototype Event HandlingNodeJS:对象原型事件处理
【发布时间】:2014-01-13 16:07:35
【问题描述】:

我有以下代码....

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();

但是当我运行它时,服务器正在监听但监听事件没有触发。

我不知道我是否遗漏了一些琐碎的事情。任何帮助将不胜感激。

谢谢。

【问题讨论】:

    标签: node.js events object prototype


    【解决方案1】:

    您将“连接”侦听器误认为“正在侦听”侦听器。检查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.');
    }
    

    【讨论】:

    • 非常感谢!这么简单的错误!这只是证明我仍然是一个 NodeJS n00b!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-10
    • 2012-02-04
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 2019-11-18
    • 1970-01-01
    相关资源
    最近更新 更多