Emitting event in Node.js

半世苍凉 提交于 2019-12-13 07:36:38

问题


I'm trying to teach myself both javascript and nodejs at the same time here and have not been able to get custom event emitting working. I am not receiving any errors, just not seeing the event being emitted. Is someone able to point out my (likely obvious) logical error?

I have a class declared in a separate module:

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


function logger(){
    var logpath, initialised, logstream;
    events.EventEmitter.call(this);
}
util.inherits(logger, events.EventEmitter);

logger.prototype.init = function(){
    this.emit( 'initialised' );
}

exports.logger = logger;

And then a main file:

var logger = require( "./logManager" ).logger;

var myLogger = new logger;

myLogger.init();

myLogger.on( 'initialised' ){
     console.log( "IT'S ALIVE!" );
}

回答1:


First off, you have a syntax error in your main file. When you attach an event handler, that event handler is always a function, and the signature is on(eventName, eventHandler), so you need:

myLogger.on('initialised', function() {
    console.log("IT'S ALIVE!");
});

Also, you have to attach the event handler before you call init, or you will miss the event, so in full:

var logger = require( "./logManager" ).logger;

var myLogger = new logger;

myLogger.on('initialised', function() {
    console.log("IT'S ALIVE!");
});

myLogger.init();


来源:https://stackoverflow.com/questions/9479765/emitting-event-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!