DIV CSS 佈局教程網

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

方法說明:

發射event事件,傳遞若干可選參數到事件監聽器的參數表。

語法:

代碼如下:
emitter.emit(event, [arg1], [arg2], [...])

接收參數:

event                      事件類型

arg1 ~ argN           傳遞的參數(多個)

例子:

代碼如下:
var  events = require('events');
var emitter = new events.EventEmitter();
 
emitter.on('someEvent', function(arg1, arg2){
    console.log('listener1', arg1, arg2);
})
 
emitter.on('someEvent', function(arg1, arg2){
    console.log('listener2', arg1, arg2);
})
 
emitter.emit('someEvent', 'byvoid', 1991);

源碼:

代碼如下:
EventEmitter.prototype.emit = function(type) {
  var er, handler, len, args, i, listeners;
  if (!this._events)
    this._events = {};
  // If there is no 'error' event listener then throw.
  if (type === 'error') {
    if (!this._events.error ||
        (util.isObject(this._events.error) && !this._events.error.length)) {
      er = arguments[1];
      if (this.domain) {
        if (!er) er = new TypeError('Uncaught, unspecified "error" event.');
        er.domainEmitter = this;
        er.domain = this.domain;
        er.domainThrown = false;
        this.domain.emit('error', er);
      } else if (er instanceof Error) {
        throw er; // Unhandled 'error' event
      } else {
        throw TypeError('Uncaught, unspecified "error" event.');
      }
      return false;
    }
  }
  handler = this._events[type];
  if (util.isUndefined(handler))
    return false;
  if (this.domain && this !== process)
    this.domain.enter();
  if (util.isFunction(handler)) {
    switch (arguments.length) {
      // fast cases
      case 1:
        handler.call(this);
        break;
      case 2:
        handler.call(this, arguments[1]);
        break;
      case 3:
        handler.call(this, arguments[1], arguments[2]);
        break;
      // slower
      default:
        len = arguments.length;
        args = new Array(len - 1);
        for (i = 1; i < len; i++)
          args[i - 1] = arguments[i];
        handler.apply(this, args);
    }
  } else if (util.isObject(handler)) {
    len = arguments.length;
    args = new Array(len - 1);
    for (i = 1; i < len; i++)
      args[i - 1] = arguments[i];
    listeners = handler.slice();
    len = listeners.length;
    for (i = 0; i < len; i++)
      listeners[i].apply(this, args);
  }
  if (this.domain && this !== process)
    this.domain.exit();
  return true;
};

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