有些事件我們只關心「第一次」,例如初次連線、首次載入等。這時若用一般的 on 註冊,監聽器會被反覆觸發。解法就是 emitter.once。
它會為指定事件註冊一個「單次」監聽器,這個監聽器最多只會被觸發一次,觸發後立刻自動解除註冊。
emitter.once(event, listener)
server.once('connection', function (stream) {
console.log('Ah, we have our first user!');
});
如此一來,不論後續有多少使用者連線,這段訊息都只會在「第一位使用者」進來時印出一次。
它的實作相當巧妙——內部包裝了一個名為 g 的中間函數,在真正執行監聽器之前先把自己移除,藉此實現「觸發即失效」的效果:
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;
};
這正是事件驅動設計中非常實用的小技巧。