node.js中的emitter.emit方法使用说明
方法说明:
发射event事件,传递若干可选参数到事件监听器的参数表。
语法:
emitter.emit(event,[arg1],[arg2],[...])
接收参数:
event 事件类型
arg1~argN 传递的参数(多个)
例子:
var events=require('events');
varemitter=newevents.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){
varer,handler,len,args,i,listeners;
if(!this._events)
this._events={};
//Ifthereisno'error'eventlistenerthenthrow.
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=newTypeError('Uncaught,unspecified"error"event.');
er.domainEmitter=this;
er.domain=this.domain;
er.domainThrown=false;
this.domain.emit('error',er);
}elseif(erinstanceofError){
thrower;//Unhandled'error'event
}else{
throwTypeError('Uncaught,unspecified"error"event.');
}
returnfalse;
}
}
handler=this._events[type];
if(util.isUndefined(handler))
returnfalse;
if(this.domain&&this!==process)
this.domain.enter();
if(util.isFunction(handler)){
switch(arguments.length){
//fastcases
case1:
handler.call(this);
break;
case2:
handler.call(this,arguments[1]);
break;
case3:
handler.call(this,arguments[1],arguments[2]);
break;
//slower
default:
len=arguments.length;
args=newArray(len-1);
for(i=1;i<len;i++)
args[i-1]=arguments[i];
handler.apply(this,args);
}
}elseif(util.isObject(handler)){
len=arguments.length;
args=newArray(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();
returntrue;
};