node.js中的events.emitter.removeListener方法使用说明_node.js
程序员文章站
2022-04-30 22:03:26
...
方法说明:
emitter.removeListener(event, listener)
var callback = function(stream) {
console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!util.isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(util.isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (util.isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
移除指定事件的某个监听器。
语法:
复制代码 代码如下:
emitter.removeListener(event, listener)
接收参数:
event (string) 事件类型
listener (function) 已注册过的监听器
例子:
复制代码 代码如下:
var callback = function(stream) {
console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
源码:
复制代码 代码如下:
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!util.isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(util.isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (util.isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
推荐阅读
-
Node.js中关于多进程模块Cluster的详细介绍以及如何使用
-
node.js中的fs.linkSync方法使用说明_node.js
-
Node.js使用Express.Router的方法
-
node.js监听文件变化的实现方法
-
C#Url操作类封装、仿Node.Js中的Url模块实例
-
Node.js中的process.nextTick使用实例
-
推荐分享Node.js中18个值得了解的Web框架和工具
-
nodejs中简单实现Javascript Promise机制的实例_node.js
-
node.js请求HTTPS报错:UNABLE_TO_VERIFY_LEAF_SIGNATURE\的解决方法
-
Node.JS段点续传:Nginx配置文件分段下载功能的实现方法_node.js