node.js中的emitter.on方法使用說明
更新時間:2014年12月10日 09:54:31 投稿:junjie
這篇文章主要介紹了node.js中的emitter.on方法使用說明,本文介紹了emitter.on的方法說明、語法、接收參數(shù)、使用實例和實現(xiàn)源碼,需要的朋友可以參考下
方法說明:
為指定事件注冊一個監(jiān)聽器。
語法:
復制代碼 代碼如下:
emitter.on(event, listener)
emitter.addListener(event, listener)
接收參數(shù):
event (string) 事件類型
listener (function) 觸發(fā)事件時的回調(diào)函數(shù)
例子:
復制代碼 代碼如下:
server.on('connection', function (stream) {
console.log('someone connected!');
});
源碼:
復制代碼 代碼如下:
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;
};
相關文章
node 利用進程通信實現(xiàn)Cluster共享內(nèi)存
本篇文章主要介紹了node 利用進程通信實現(xiàn)Cluster共享內(nèi)存,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-10-10
利用adb shell和node.js實現(xiàn)抖音搶紅包功能(推薦)
這篇文章主要介紹了利用adb shell和node.js實現(xiàn)抖音搶紅包功能,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2018-02-02
詳解Express筆記之動態(tài)渲染HTML(新手入坑)
這篇文章主要介紹了詳解Express筆記之動態(tài)渲染HTML(新手入坑),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-12-12
Node.js?中的?module.exports?與?exports區(qū)別介紹
這篇文章主要介紹了Node.js中的module.exports與exports區(qū)別介紹,每個模塊中都有module對象,存放了當前模塊相關的信息,更多相關內(nèi)容需要的朋友可以參考一下2022-09-09
Node.js Sequelize如何實現(xiàn)數(shù)據(jù)庫的讀寫分離
Sequelize是一個易于使用,支持多SQL方言(dialect)的對象-關系映射框架(ORM),這個庫完全采用JavaScript開發(fā)并且能夠用在Node.JS環(huán)境中。它當前支持MySQL, MariaDB, SQLite 和 PostgreSQL 數(shù)據(jù)庫。在Node.js中,使用 Sequelize操作數(shù)據(jù)庫時,同樣支持讀寫分離。2016-10-10

