DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> node.js中的emitter.on方法教程使用說明詳解
node.js中的emitter.on方法教程使用說明詳解
編輯:關於JavaScript     

方法說明:

為指定事件注冊一個監聽器。

語法:

代碼如下:
emitter.on(event, listener)
emitter.addListener(event, listener)

接收參數:

event            (string)             事件類型
listener         (function)         觸發事件時的回調函數

例子:

代碼如下:
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;
};

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved