Home  >  Article  >  Web Front-end  >  Instructions for using the emitter.on method in node.js_node.js

Instructions for using the emitter.on method in node.js_node.js

WBOY
WBOYOriginal
2016-05-16 16:27:501999browse

Method description:

Register a listener for the specified event.

Grammar:

Copy code The code is as follows:

emitter.on(event, listener)
emitter.addListener(event, listener)

Receive parameters:

event (string) Event type
listener (function) The callback function when an event is triggered

Example:

Copy code The code is as follows:

server.on('connection', function (stream) {
console.log('someone connected!');
});

Source code:

Copy code The code is as follows:

EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!util.isFunction(listener))
Throw TypeError('listener must be a function');
if (!this._events)
This._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
This.emit('newListener', type,
                util.isFunction(listener.listener) ?
Listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
This._events[type] = listener;
else if (util.isObject(this._events[type]))
// If we've already got an array, just append.
This._events[type].push(listener);
else
// Adding the second element, need to change to array.
This._events[type] = [this._events[type], listener];
// Check for listener leak
if (util.isObject(this._events[type]) && !this._events[type].warned) {
var m;
If (!util.isUndefined(this._maxListeners)) {
        m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
If (m && m > 0 && this._events[type].length > m) {
This._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory '
'leak detected. %d listeners added. '
                         'Use emitter.setMaxListeners() to increase limit.',
This._events[type].length);
console.trace();
}
}
return this;
};
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn