我一直在编写 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/