Skip to content
Browse files

Added support for removing listeners that have been added to the even…

…ts hash using the `.once` method.
  • Loading branch information...
1 parent 602a463 commit d8fdabff81860bb828f583d8bdf0ad8bfffc5595 @3rd-Eden committed Mar 18, 2011
Showing with 20 additions and 6 deletions.
  1. +20 −6 lib/events.js
View
26 lib/events.js
@@ -138,10 +138,13 @@ EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
var self = this;
- self.on(type, function g() {
+ function g() {
self.removeListener(type, g);
listener.apply(this, arguments);
- });
+ };
+
+ g.listener = listener;
+ self.on(type, g);
return this;
};
@@ -157,12 +160,23 @@ EventEmitter.prototype.removeListener = function(type, listener) {
var list = this._events[type];
if (isArray(list)) {
- var i = list.indexOf(listener);
- if (i < 0) return this;
- list.splice(i, 1);
+ var position = -1;
+ for (var i = 0, length = list.length; i < length; i++) {
+ if (list[i] === listener ||
+ (list[i].listener && list[i].listener === listener))
+ {
+ position = i;
+ break;
+ }
+ }
+
+ if (position < 0) return this;
+ list.splice(position, 1);
if (list.length == 0)
delete this._events[type];
- } else if (this._events[type] === listener) {
+ } else if (list === listener ||
+ (list.listener && list.listener === listener))
+ {
delete this._events[type];
}

0 comments on commit d8fdabf

Please sign in to comment.
Something went wrong with that request. Please try again.