node.js中的events.emitter.removeListener方法使用说明
方法说明:
移除指定事件的某个监听器。
语法:
emitter.removeListener(event,listener)
接收参数:
event (string) 事件类型
listener (function) 已注册过的监听器
例子:
varcallback=function(stream){
console.log('someoneconnected!');
};
server.on('connection',callback);
//...
server.removeListener('connection',callback);
源码:
//emitsa'removeListener'eventiffthelistenerwasremoved
EventEmitter.prototype.removeListener=function(type,listener){
varlist,position,length,i;
if(!util.isFunction(listener))
throwTypeError('listenermustbeafunction');
if(!this._events||!this._events[type])
returnthis;
list=this._events[type];
length=list.length;
position=-1;
if(list===listener||
(util.isFunction(list.listener)&&list.listener===listener)){
deletethis._events[type];
if(this._events.removeListener)
this.emit('removeListener',type,listener);
}elseif(util.isObject(list)){
for(i=length;i-->0;){
if(list[i]===listener||
(list[i].listener&&list[i].listener===listener)){
position=i;
break;
}
}
if(position<0)
returnthis;
if(list.length===1){
list.length=0;
deletethis._events[type];
}else{
list.splice(position,1);
}
if(this._events.removeListener)
this.emit('removeListener',type,listener);
}
returnthis;
};