diff --git a/doc/api.txt b/doc/api.txt index a6ca6bf11a..c745bc8716 100644 --- a/doc/api.txt +++ b/doc/api.txt @@ -263,6 +263,9 @@ server.addListener("connection", function (socket) { Remove a listener from the listener array for the specified event. *Caution*: changes array indices in the listener array behind the listener. ++emitter.removeAllListeners(event)+ :: +Removes all listeners from the listener array for the specified event. + +emitter.listeners(event)+ :: Returns an array of listeners for the specified event. This array can be manipulated, e.g. to remove listeners. diff --git a/src/node.js b/src/node.js index 4fcd67d5ad..0398ba261f 100644 --- a/src/node.js +++ b/src/node.js @@ -186,6 +186,12 @@ var eventsModule = createInternalModule('events', function (exports) { return this; }; + process.EventEmitter.prototype.removeAllListeners = function (type) { + // does not use listeners(), so no side effect of creating _events[type] + if (!type || !this._events || !this._events.hasOwnProperty(type)) return this; + this._events[type].length = 0; + }; + process.EventEmitter.prototype.listeners = function (type) { if (!this._events) this._events = {}; if (!this._events.hasOwnProperty(type)) this._events[type] = []; diff --git a/test/simple/test-event-emitter-modify-in-emit.js b/test/simple/test-event-emitter-modify-in-emit.js index 25c2255873..1dd94ba712 100644 --- a/test/simple/test-event-emitter-modify-in-emit.js +++ b/test/simple/test-event-emitter-modify-in-emit.js @@ -30,3 +30,9 @@ assert.deepEqual(["callback1", "callback2"], callbacks_called); e.emit("foo"); assert.equal(0, e.listeners("foo").length); assert.deepEqual(["callback1", "callback2"], callbacks_called); + +e.addListener("foo", callback1); +e.addListener("foo", callback2); +assert.equal(2, e.listeners("foo").length) +e.removeAllListeners("foo") +assert.equal(0, e.listeners("foo").length) \ No newline at end of file