javascript - npm 包中的事件监听器在哪里定义?

标签 javascript node.js npm dom-events irc

我一直在编写 IRC bot 的代码在nodejs中作为学习项目。我经常遇到如下事件监听器:

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

问题:我一直在到处寻找这个 addListener 定义/解释位置的解释。我找不到任何东西。它来自 npm 中的 irc 包,即使在搜索了 irc 包源中的每个 github 文件后,我也没有找到该字符串的实例addListener

这是怎么回事?我如何弄清楚这个 addListener 是如何工作的、IRC 事件列表是什么(除了“消息”之外)等等?

最佳答案

看这里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.

它通常添加到对象 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!"

对于你的 irc-bot,你可以在 https://github.com/martynsmith/node-irc/blob/master/lib%2Firc.js 找到这个刺痛。第603行

util.inherits(Client, process.EventEmitter);

事件通过像

这样的结构触发
self.emit('connect'); // same file  L:665

关于javascript - npm 包中的事件监听器在哪里定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27835426/

相关文章:

javascript - Turbolinks 总是像往常一样加载页面

javascript - 使用 jQuery 更新表

angular - "You seem to not be depending on "@ Angular/核心 "."

reactjs - React Native 重复模块命名冲突

Javascript 快速变量赋值

javascript - 通过 PHP 流式传输时,Safari 中的音频持续时间总是返回无穷大

javascript - 从 discord.js 中的消息获取表情符号 url

angular - 如何编写 Angular2 npm 模块 - Angular2 RC 6

php - 类似于 niftyplayer 的可编写脚本的 mp3 播放器

regex - 如何创建处理如下 URL 的 Express 路由?