這篇文章主要介紹了node.js中的events.emitter.once方法使用說明,本文介紹了events.emitter.once的方法說明、語法、接收參數、使用實例和實現源碼,需要的朋友可以參考下
方法說明:
為指定事件注冊一個 單次 監聽器,所以監聽器至多只會觸發一次,觸發后立即解除該監聽器。
語法:
復制代碼代碼如下:
emitter.once(event, listener)
接收參數:
event (string) 事件類型
listener (function) 觸發事件時的回調函數
例子:
復制代碼代碼如下:
server.once('connection', function (stream) {
console.log('Ah, we have our first user!');
});
源碼:
復制代碼代碼如下:
EventEmitter.prototype.once = function(type, listener) {
if (!util.isFunction(listener))
throw TypeError('listener must be a function');
function g() {
this.removeListener(type, g);
listener.apply(this, arguments);
}
g.listener = listener;
this.on(type, g);
return this;
};