javascriptnode.jsnpmdom-eventsirc

Where are event listeners defined in npm packages?


I've been working on coding an IRC bot in nodejs as a learning project. I've been frequently coming across event listeners such as the following:

bot.addListener("message", function(from, to, text, message) {
.
.
.
});

Problem: I've been looking everywhere for an explanation of where this addListener is defined/explained. I can't find anything. It is from the irc package in npm, and even after searching every github file in the irc package source, I find no instance of the string addListener.

What's going on here? How do I figure out how this addListener is working, what the list of IRC events are (besides just "message"), and so forth?


Solution

  • Look here http://nodejs.org/docs/latest/api/events.html#events_emitter_addlistener_event_listener

    emitter.addListener(event, listener)

    emitter.on(event, listener)

    Adds a listener to the end of the listeners array for the specified event. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of event and listener will result in the listener being added multiple times.

    server.on('connection', function (stream) {   console.log('someone
    connected!'); }); Returns emitter, so calls can be chained.
    

    It usually added to object with http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor

    util.inherits(constructor, superConstructor)# Inherit the prototype methods from one constructor into another. The prototype of constructor will be set to a new object created from superConstructor.

    As an additional convenience, superConstructor will be accessible through the constructor.super_ property.

    var util = require("util"); var events = require("events");
    
    function MyStream() {
        events.EventEmitter.call(this); }
    
    util.inherits(MyStream, events.EventEmitter);
    
    MyStream.prototype.write = function(data) {
        this.emit("data", data); }
    
    var stream = new MyStream();
    
    console.log(stream instanceof events.EventEmitter); // true console.log(MyStream.super_ === events.EventEmitter); // true
    
    stream.on("data", function(data) {
        console.log('Received data: "' + data + '"'); }) stream.write("It works!"); // Received data: "It works!"
    

    For your irc-bot you can find thid sting at https://github.com/martynsmith/node-irc/blob/master/lib%2Firc.js line 603

    util.inherits(Client, process.EventEmitter);
    

    and event fired with construction like

    self.emit('connect'); // same file  L:665