Description of Emitter.on method used in Node.js _node.js

Source: Internet
Author: User
Tags emit

Method Description:

Registers a listener for the specified event.

Grammar:

Copy Code code as follows:

Emitter.on (event, listener)
Emitter.addlistener (event, listener)

Receive parameters:

Event (String) events type
callback function when listener (function) triggers an event

Example:

Copy Code code as follows:

Server.on (' Connection ', function (stream) {
Console.log (' someone connected! ');
});

Source:

Copy Code code 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 into the case, that type = = "Newlistener"! Before
Adding it to the listeners, the 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;
};

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.