From a6ee3bac85c84c1a24c1a2aa621f77ba5d1c0bb9 Mon Sep 17 00:00:00 2001 From: Peteris Krumins Date: Tue, 12 Oct 2010 23:52:26 +0300 Subject: [PATCH] Add EventEmitter.prototype.once --- lib/events.js | 10 +++++++++- test/simple/test-event-emitter-once.js | 20 ++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 test/simple/test-event-emitter-once.js diff --git a/lib/events.js b/lib/events.js index e0480b0..cf9651a 100644 --- a/lib/events.js +++ b/lib/events.js @@ -76,6 +76,14 @@ EventEmitter.prototype.addListener = function (type, listener) { EventEmitter.prototype.on = EventEmitter.prototype.addListener; +EventEmitter.prototype.once = function (type, listener) { + var self = this; + self.on(type, function g () { + self.removeListener(type, g); + listener.apply(this, arguments); + }); +}; + EventEmitter.prototype.removeListener = function (type, listener) { if ('function' !== typeof listener) { throw new Error('removeListener only takes instances of Function'); @@ -112,4 +120,4 @@ EventEmitter.prototype.listeners = function (type) { this._events[type] = [this._events[type]]; } return this._events[type]; -}; \ No newline at end of file +}; diff --git a/test/simple/test-event-emitter-once.js b/test/simple/test-event-emitter-once.js new file mode 100644 index 0000000..8639231 --- /dev/null +++ b/test/simple/test-event-emitter-once.js @@ -0,0 +1,20 @@ +common = require("../common"); +assert = common.assert +var events = require('events'); + +var e = new events.EventEmitter(); +var times_hello_emited = 0; + +e.once("hello", function (a, b) { + times_hello_emited++; +}); + +e.emit("hello", "a", "b"); +e.emit("hello", "a", "b"); +e.emit("hello", "a", "b"); +e.emit("hello", "a", "b"); + +process.addListener("exit", function () { + assert.equal(1, times_hello_emited); +}); + -- 2.7.4