Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

events

Package Overview
Dependencies
Maintainers
3
Versions
17
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

events - npm Package Compare versions

Comparing version 1.1.1 to 2.0.0

579

events.js

@@ -22,4 +22,12 @@ // Copyright Joyent, Inc. and other Node contributors.

var objectCreate = Object.create || objectCreatePolyfill
var objectKeys = Object.keys || objectKeysPolyfill
var bind = Function.prototype.bind || functionBindPolyfill
function EventEmitter() {
this._events = this._events || {};
if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
this._events = objectCreate(null);
this._eventsCount = 0;
}
this._maxListeners = this._maxListeners || undefined;

@@ -37,9 +45,33 @@ }

// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
var defaultMaxListeners = 10;
var hasDefineProperty;
try {
var o = {};
if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
hasDefineProperty = o.x === 0;
} catch (err) { hasDefineProperty = false }
if (hasDefineProperty) {
Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
enumerable: true,
get: function() {
return defaultMaxListeners;
},
set: function(arg) {
// check whether the input is a positive number (whose value is zero or
// greater and not a NaN).
if (typeof arg !== 'number' || arg < 0 || arg !== arg)
throw new TypeError('"defaultMaxListeners" must be a positive number');
defaultMaxListeners = arg;
}
});
} else {
EventEmitter.defaultMaxListeners = defaultMaxListeners;
}
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
if (typeof n !== 'number' || n < 0 || isNaN(n))
throw new TypeError('"n" argument must be a positive number');
this._maxListeners = n;

@@ -49,52 +81,121 @@ return this;

EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
function $getMaxListeners(that) {
if (that._maxListeners === undefined)
return EventEmitter.defaultMaxListeners;
return that._maxListeners;
}
if (!this._events)
this._events = {};
EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
return $getMaxListeners(this);
};
// These standalone emit* functions are used to optimize calling of event
// handlers for fast cases because emit() itself often has a variable number of
// arguments and can be deoptimized because of that. These functions always have
// the same number of arguments and thus do not get deoptimized, so the code
// inside them can execute faster.
function emitNone(handler, isFn, self) {
if (isFn)
handler.call(self);
else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i)
listeners[i].call(self);
}
}
function emitOne(handler, isFn, self, arg1) {
if (isFn)
handler.call(self, arg1);
else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i)
listeners[i].call(self, arg1);
}
}
function emitTwo(handler, isFn, self, arg1, arg2) {
if (isFn)
handler.call(self, arg1, arg2);
else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i)
listeners[i].call(self, arg1, arg2);
}
}
function emitThree(handler, isFn, self, arg1, arg2, arg3) {
if (isFn)
handler.call(self, arg1, arg2, arg3);
else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i)
listeners[i].call(self, arg1, arg2, arg3);
}
}
function emitMany(handler, isFn, self, args) {
if (isFn)
handler.apply(self, args);
else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i)
listeners[i].apply(self, args);
}
}
EventEmitter.prototype.emit = function emit(type) {
var er, handler, len, args, i, events;
var doError = (type === 'error');
events = this._events;
if (events)
doError = (doError && events.error == null);
else if (!doError)
return false;
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
if (doError) {
if (arguments.length > 1)
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
throw err;
}
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Unhandled "error" event. (' + er + ')');
err.context = er;
throw err;
}
return false;
}
handler = this._events[type];
handler = events[type];
if (isUndefined(handler))
if (!handler)
return false;
if (isFunction(handler)) {
switch (arguments.length) {
var isFn = typeof handler === 'function';
len = arguments.length;
switch (len) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
case 1:
emitNone(handler, isFn, this);
break;
case 2:
emitOne(handler, isFn, this, arguments[1]);
break;
case 3:
emitTwo(handler, isFn, this, arguments[1], arguments[2]);
break;
case 4:
emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
default:
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
emitMany(handler, isFn, this, args);
}

@@ -105,45 +206,62 @@

EventEmitter.prototype.addListener = function(type, listener) {
function _addListener(target, type, listener, prepend) {
var m;
var events;
var existing;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (typeof listener !== 'function')
throw new TypeError('"listener" argument must be a function');
if (!this._events)
this._events = {};
events = target._events;
if (!events) {
events = target._events = objectCreate(null);
target._eventsCount = 0;
} else {
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (events.newListener) {
target.emit('newListener', type,
listener.listener ? listener.listener : listener);
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
// Re-assign `events` because a newListener handler could have caused the
// this._events to be assigned to a new object
events = target._events;
}
existing = events[type];
}
if (!this._events[type])
if (!existing) {
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
existing = events[type] = listener;
++target._eventsCount;
} else {
if (typeof existing === 'function') {
// Adding the second element, need to change to array.
existing = events[type] =
prepend ? [listener, existing] : [existing, listener];
} else {
m = EventEmitter.defaultMaxListeners;
// If we've already got an array, just append.
if (prepend) {
existing.unshift(listener);
} else {
existing.push(listener);
}
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
// Check for listener leak
if (!existing.warned) {
m = $getMaxListeners(target);
if (m && m > 0 && existing.length > m) {
existing.warned = true;
var w = new Error('Possible EventEmitter memory leak detected. ' +
existing.length + ' "' + String(type) + '" listeners ' +
'added. Use emitter.setMaxListeners() to ' +
'increase limit.');
w.name = 'MaxListenersExceededWarning';
w.emitter = target;
w.type = type;
w.count = existing.length;
if (typeof console === 'object' && console.warn) {
console.warn('%s: %s', w.name, w.message);
}
}

@@ -153,3 +271,7 @@ }

return this;
return target;
}
EventEmitter.prototype.addListener = function addListener(type, listener) {
return _addListener(this, type, listener, false);
};

@@ -159,150 +281,245 @@

EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
EventEmitter.prototype.prependListener =
function prependListener(type, listener) {
return _addListener(this, type, listener, true);
};
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
function onceWrapper() {
if (!this.fired) {
this.target.removeListener(this.type, this.wrapFn);
this.fired = true;
switch (arguments.length) {
case 0:
return this.listener.call(this.target);
case 1:
return this.listener.call(this.target, arguments[0]);
case 2:
return this.listener.call(this.target, arguments[0], arguments[1]);
case 3:
return this.listener.call(this.target, arguments[0], arguments[1],
arguments[2]);
default:
var args = new Array(arguments.length);
for (var i = 0; i < args.length; ++i)
args[i] = arguments[i];
this.listener.apply(this.target, args);
}
}
}
g.listener = listener;
this.on(type, g);
function _onceWrap(target, type, listener) {
var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
var wrapped = bind.call(onceWrapper, state);
wrapped.listener = listener;
state.wrapFn = wrapped;
return wrapped;
}
EventEmitter.prototype.once = function once(type, listener) {
if (typeof listener !== 'function')
throw new TypeError('"listener" argument must be a function');
this.on(type, _onceWrap(this, type, listener));
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
EventEmitter.prototype.prependOnceListener =
function prependOnceListener(type, listener) {
if (typeof listener !== 'function')
throw new TypeError('"listener" argument must be a function');
this.prependListener(type, _onceWrap(this, type, listener));
return this;
};
if (!isFunction(listener))
throw TypeError('listener must be a function');
// Emits a 'removeListener' event if and only if the listener was removed.
EventEmitter.prototype.removeListener =
function removeListener(type, listener) {
var list, events, position, i, originalListener;
if (!this._events || !this._events[type])
return this;
if (typeof listener !== 'function')
throw new TypeError('"listener" argument must be a function');
list = this._events[type];
length = list.length;
position = -1;
events = this._events;
if (!events)
return this;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
list = events[type];
if (!list)
return this;
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
if (list === listener || list.listener === listener) {
if (--this._eventsCount === 0)
this._events = objectCreate(null);
else {
delete events[type];
if (events.removeListener)
this.emit('removeListener', type, list.listener || listener);
}
} else if (typeof list !== 'function') {
position = -1;
for (i = list.length - 1; i >= 0; i--) {
if (list[i] === listener || list[i].listener === listener) {
originalListener = list[i].listener;
position = i;
break;
}
}
if (position < 0)
return this;
if (position === 0)
list.shift();
else
spliceOne(list, position);
if (list.length === 1)
events[type] = list[0];
if (events.removeListener)
this.emit('removeListener', type, originalListener || listener);
}
}
if (position < 0)
return this;
};
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
EventEmitter.prototype.removeAllListeners =
function removeAllListeners(type) {
var listeners, events, i;
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
events = this._events;
if (!events)
return this;
return this;
};
// not listening for removeListener, no need to emit
if (!events.removeListener) {
if (arguments.length === 0) {
this._events = objectCreate(null);
this._eventsCount = 0;
} else if (events[type]) {
if (--this._eventsCount === 0)
this._events = objectCreate(null);
else
delete events[type];
}
return this;
}
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
var keys = objectKeys(events);
var key;
for (i = 0; i < keys.length; ++i) {
key = keys[i];
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = objectCreate(null);
this._eventsCount = 0;
return this;
}
if (!this._events)
return this;
listeners = events[type];
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
if (typeof listeners === 'function') {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
for (i = listeners.length - 1; i >= 0; i--) {
this.removeListener(type, listeners[i]);
}
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
return this;
};
listeners = this._events[type];
EventEmitter.prototype.listeners = function listeners(type) {
var evlistener;
var ret;
var events = this._events;
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
if (!events)
ret = [];
else {
evlistener = events[type];
if (!evlistener)
ret = [];
else if (typeof evlistener === 'function')
ret = [evlistener.listener || evlistener];
else
ret = unwrapListeners(evlistener);
}
delete this._events[type];
return this;
return ret;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
EventEmitter.listenerCount = function(emitter, type) {
if (typeof emitter.listenerCount === 'function') {
return emitter.listenerCount(type);
} else {
return listenerCount.call(emitter, type);
}
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
EventEmitter.prototype.listenerCount = listenerCount;
function listenerCount(type) {
var events = this._events;
if (isFunction(evlistener))
if (events) {
var evlistener = events[type];
if (typeof evlistener === 'function') {
return 1;
else if (evlistener)
} else if (evlistener) {
return evlistener.length;
}
}
return 0;
};
}
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
EventEmitter.prototype.eventNames = function eventNames() {
return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
};
function isFunction(arg) {
return typeof arg === 'function';
// About 1.5x faster than the two-arg version of Array#splice().
function spliceOne(list, index) {
for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
list[i] = list[k];
list.pop();
}
function isNumber(arg) {
return typeof arg === 'number';
function arrayClone(arr, n) {
var copy = new Array(n);
for (var i = 0; i < n; ++i)
copy[i] = arr[i];
return copy;
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
function unwrapListeners(arr) {
var ret = new Array(arr.length);
for (var i = 0; i < ret.length; ++i) {
ret[i] = arr[i].listener || arr[i];
}
return ret;
}
function isUndefined(arg) {
return arg === void 0;
function objectCreatePolyfill(proto) {
var F = function() {};
F.prototype = proto;
return new F;
}
function objectKeysPolyfill(obj) {
var keys = [];
for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
keys.push(k);
}
return k;
}
function functionBindPolyfill(context) {
var fn = this;
return function () {
return fn.apply(context, arguments);
};
}

@@ -0,1 +1,13 @@

# 2.0.0 (2018-02-02)
- Update to events code from node.js 8.x
- Adds `prependListener()` and `prependOnceListener()`
- Adds `eventNames()` method
- (semver major) Unwrap `once()` listeners in `listeners()`
- copy tests from node.js
Note that this version doubles the gzipped size, jumping from 1.1KB to 2.1KB,
due to new methods and runtime performance improvements. Be aware of that when
upgrading.
# 1.1.1 (2016-06-22)

@@ -2,0 +14,0 @@

{
"name": "events",
"id": "events",
"version": "1.1.1",
"version": "2.0.0",
"description": "Node's event emitter for all engines.",

@@ -26,4 +26,6 @@ "keywords": [

"devDependencies": {
"mocha": "~1.21.4",
"zuul": "~1.10.2"
"isarray": "^2.0.2",
"mocha": "^3.5.3",
"object-keys": "^1.0.11",
"zuul": "^3.11.1"
},

@@ -34,2 +36,2 @@ "scripts": {

"license": "MIT"
}
}

@@ -0,1 +1,3 @@

# Status: [Maintainer Needed](https://github.com/Gozala/events/issues/43)
# events [![Build Status](https://travis-ci.org/Gozala/events.png?branch=master)](https://travis-ci.org/Gozala/events)

@@ -14,3 +16,3 @@

```javascript
var EventEmitter = require('events').EventEmitter
var EventEmitter = require('events')
```

@@ -17,0 +19,0 @@

@@ -22,43 +22,91 @@ // Copyright Joyent, Inc. and other Node contributors.

var common = require('./common');
var assert = require('assert');
var events = require('../');
var EventEmitter = require('../');
var e = new events.EventEmitter();
{
var ee = new EventEmitter();
var events_new_listener_emitted = [];
var listeners_new_listener_emitted = [];
var events_new_listener_emited = [];
var listeners_new_listener_emited = [];
var times_hello_emited = 0;
// Sanity check
assert.strictEqual(ee.addListener, ee.on);
// sanity check
assert.equal(e.addListener, e.on);
ee.on('newListener', function(event, listener) {
// Don't track newListener listeners.
if (event === 'newListener')
return;
e.on('newListener', function(event, listener) {
console.log('newListener: ' + event);
events_new_listener_emited.push(event);
listeners_new_listener_emited.push(listener);
});
events_new_listener_emitted.push(event);
listeners_new_listener_emitted.push(listener);
});
function hello(a, b) {
console.log('hello');
times_hello_emited += 1;
assert.equal('a', a);
assert.equal('b', b);
}
e.on('hello', hello);
var hello = common.mustCall(function(a, b) {
assert.strictEqual('a', a);
assert.strictEqual('b', b);
});
var foo = function() {};
e.once('foo', foo);
ee.once('newListener', function(name, listener) {
assert.strictEqual(name, 'hello');
assert.strictEqual(listener, hello);
console.log('start');
var listeners = this.listeners('hello');
assert.ok(Array.isArray(listeners));
assert.strictEqual(listeners.length, 0);
});
e.emit('hello', 'a', 'b');
ee.on('hello', hello);
ee.once('foo', assert.fail);
assert.ok(Array.isArray(events_new_listener_emitted));
assert.strictEqual(events_new_listener_emitted.length, 2);
assert.strictEqual(events_new_listener_emitted[0], 'hello');
assert.strictEqual(events_new_listener_emitted[1], 'foo');
assert.ok(Array.isArray(listeners_new_listener_emitted));
assert.strictEqual(listeners_new_listener_emitted.length, 2);
assert.strictEqual(listeners_new_listener_emitted[0], hello);
assert.strictEqual(listeners_new_listener_emitted[1], assert.fail);
ee.emit('hello', 'a', 'b');
}
// just make sure that this doesn't throw:
var f = new events.EventEmitter();
f.setMaxListeners(0);
{
var f = new EventEmitter();
assert.deepEqual(['hello', 'foo'], events_new_listener_emited);
assert.deepEqual([hello, foo], listeners_new_listener_emited);
assert.equal(1, times_hello_emited);
f.setMaxListeners(0);
}
{
var listen1 = function() {};
var listen2 = function() {};
var ee = new EventEmitter();
ee.once('newListener', function() {
var listeners = ee.listeners('hello');
assert.ok(Array.isArray(listeners));
assert.strictEqual(listeners.length, 0);
ee.once('newListener', function() {
var listeners = ee.listeners('hello');
assert.ok(Array.isArray(listeners));
assert.strictEqual(listeners.length, 0);
});
ee.on('hello', listen2);
});
ee.on('hello', listen1);
// The order of listeners on an event is not always the order in which the
// listeners were added.
var listeners = ee.listeners('hello');
assert.ok(Array.isArray(listeners));
assert.strictEqual(listeners.length, 2);
assert.strictEqual(listeners[0], listen2);
assert.strictEqual(listeners[1], listen1);
}
// Verify that the listener must be a function
assert.throws(function() {
var ee = new EventEmitter();
ee.on('foo', null);
}, /^TypeError: "listener" argument must be a function$/);

@@ -22,66 +22,73 @@ // Copyright Joyent, Inc. and other Node contributors.

var common = require('./common');
var assert = require('assert');
var events = require('../');
var e = new events.EventEmitter();
// default
for (var i = 0; i < 10; i++) {
e.on('default', function() {});
}
assert.ok(!e._events['default'].hasOwnProperty('warned'));
e.on('default', function() {});
assert.ok(e._events['default'].warned);
{
var e = new events.EventEmitter();
// specific
e.setMaxListeners(5);
for (var i = 0; i < 5; i++) {
e.on('specific', function() {});
}
assert.ok(!e._events['specific'].hasOwnProperty('warned'));
e.on('specific', function() {});
assert.ok(e._events['specific'].warned);
for (var i = 0; i < 10; i++) {
e.on('default', common.mustNotCall());
}
assert.ok(!e._events['default'].hasOwnProperty('warned'));
e.on('default', common.mustNotCall());
assert.ok(e._events['default'].warned);
// only one
e.setMaxListeners(1);
e.on('only one', function() {});
assert.ok(!e._events['only one'].hasOwnProperty('warned'));
e.on('only one', function() {});
assert.ok(e._events['only one'].hasOwnProperty('warned'));
// specific
e.setMaxListeners(5);
for (var i = 0; i < 5; i++) {
e.on('specific', common.mustNotCall());
}
assert.ok(!e._events['specific'].hasOwnProperty('warned'));
e.on('specific', common.mustNotCall());
assert.ok(e._events['specific'].warned);
// unlimited
e.setMaxListeners(0);
for (var i = 0; i < 1000; i++) {
e.on('unlimited', function() {});
// only one
e.setMaxListeners(1);
e.on('only one', common.mustNotCall());
assert.ok(!e._events['only one'].hasOwnProperty('warned'));
e.on('only one', common.mustNotCall());
assert.ok(e._events['only one'].hasOwnProperty('warned'));
// unlimited
e.setMaxListeners(0);
for (var i = 0; i < 1000; i++) {
e.on('unlimited', common.mustNotCall());
}
assert.ok(!e._events['unlimited'].hasOwnProperty('warned'));
}
assert.ok(!e._events['unlimited'].hasOwnProperty('warned'));
// process-wide
events.EventEmitter.defaultMaxListeners = 42;
e = new events.EventEmitter();
{
events.EventEmitter.defaultMaxListeners = 42;
var e = new events.EventEmitter();
for (var i = 0; i < 42; ++i) {
e.on('fortytwo', function() {});
for (var i = 0; i < 42; ++i) {
e.on('fortytwo', common.mustNotCall());
}
assert.ok(!e._events['fortytwo'].hasOwnProperty('warned'));
e.on('fortytwo', common.mustNotCall());
assert.ok(e._events['fortytwo'].hasOwnProperty('warned'));
delete e._events['fortytwo'].warned;
events.EventEmitter.defaultMaxListeners = 44;
e.on('fortytwo', common.mustNotCall());
assert.ok(!e._events['fortytwo'].hasOwnProperty('warned'));
e.on('fortytwo', common.mustNotCall());
assert.ok(e._events['fortytwo'].hasOwnProperty('warned'));
}
assert.ok(!e._events['fortytwo'].hasOwnProperty('warned'));
e.on('fortytwo', function() {});
assert.ok(e._events['fortytwo'].hasOwnProperty('warned'));
delete e._events['fortytwo'].warned;
events.EventEmitter.defaultMaxListeners = 44;
e.on('fortytwo', function() {});
assert.ok(!e._events['fortytwo'].hasOwnProperty('warned'));
e.on('fortytwo', function() {});
assert.ok(e._events['fortytwo'].hasOwnProperty('warned'));
// but _maxListeners still has precedence over defaultMaxListeners
events.EventEmitter.defaultMaxListeners = 42;
e = new events.EventEmitter();
e.setMaxListeners(1);
e.on('uno', function() {});
assert.ok(!e._events['uno'].hasOwnProperty('warned'));
e.on('uno', function() {});
assert.ok(e._events['uno'].hasOwnProperty('warned'));
{
events.EventEmitter.defaultMaxListeners = 42;
var e = new events.EventEmitter();
e.setMaxListeners(1);
e.on('uno', common.mustNotCall());
assert.ok(!e._events['uno'].hasOwnProperty('warned'));
e.on('uno', common.mustNotCall());
assert.ok(e._events['uno'].hasOwnProperty('warned'));
// chainable
assert.strictEqual(e, e.setMaxListeners(1));
// chainable
assert.strictEqual(e, e.setMaxListeners(1));
}

@@ -0,36 +1,82 @@

// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var assert = require('assert');
var noop = function() {};
var mustCallChecks = [];
function runCallChecks() {
var failed_count = 0;
for (var i=0 ; i< mustCallChecks.length; ++i) {
var context = mustCallChecks[i];
if (context.actual === context.expected) {
continue;
function runCallChecks(exitCode) {
if (exitCode !== 0) return;
var failed = filter(mustCallChecks, function(context) {
if ('minimum' in context) {
context.messageSegment = 'at least ' + context.minimum;
return context.actual < context.minimum;
} else {
context.messageSegment = 'exactly ' + context.exact;
return context.actual !== context.exact;
}
});
failed_count++;
console.log('Mismatched %s function calls. Expected %d, actual %d.',
context.name,
context.expected,
context.actual);
console.log(context.stack.split('\n').slice(2).join('\n'));
for (var i = 0; i < failed.length; i++) {
var context = failed[i];
console.log('Mismatched %s function calls. Expected %s, actual %d.',
context.name,
context.messageSegment,
context.actual);
// IE8 has no .stack
if (context.stack) console.log(context.stack.split('\n').slice(2).join('\n'));
}
assert(failed_count === 0);
assert.strictEqual(failed.length, 0);
}
after(runCallChecks);
exports.mustCall = function(fn, exact) {
return _mustCallInner(fn, exact, 'exact');
};
exports.mustCall = function(fn, expected) {
if (typeof expected !== 'number') expected = 1;
function _mustCallInner(fn, criteria, field) {
if (typeof criteria == 'undefined') criteria = 1;
if (typeof fn === 'number') {
criteria = fn;
fn = noop;
} else if (fn === undefined) {
fn = noop;
}
if (typeof criteria !== 'number')
throw new TypeError('Invalid ' + field + ' value: ' + criteria);
var context = {
expected: expected,
actual: 0,
stack: (new Error).stack,
stack: (new Error()).stack,
name: fn.name || '<anonymous>'
};
context[field] = criteria;
// add the exit listener only once to avoid listener leak warnings
if (mustCallChecks.length === 0) after(function() { runCallChecks(0); });
mustCallChecks.push(context);

@@ -42,2 +88,17 @@

};
}
exports.mustNotCall = function(msg) {
return function mustNotCall() {
assert.fail(msg || 'function should not have been called');
};
};
function filter(arr, fn) {
if (arr.filter) return arr.filter(fn);
var filtered = [];
for (var i = 0; i < arr.length; i++) {
if (fn(arr[i], i, arr)) filtered.push(arr[i]);
}
return filtered
}

@@ -11,3 +11,3 @@

});
}
};

@@ -14,0 +14,0 @@ require('./add-listeners.js');

@@ -15,5 +15,3 @@ // sigh... life is hard

if (!Array.isArray) {
Array.isArray = function(arr) {
return Object.prototype.toString.call(arr) === '[object Array]';
}
Array.isArray = require('isarray');
}

@@ -22,2 +22,3 @@ // Copyright Joyent, Inc. and other Node contributors.

require('./common');
var assert = require('assert');

@@ -24,0 +25,0 @@ var EventEmitter = require('../');

@@ -1,2 +0,1 @@

// Copyright Joyent, Inc. and other Node contributors.

@@ -23,22 +22,25 @@ //

require('./common');
var assert = require('assert');
var EventEmitter = require('../').EventEmitter;
var objectKeys = require('object-keys');
var e = new EventEmitter;
var e = new EventEmitter();
var fl; // foo listeners
fl = e.listeners('foo');
assert(Array.isArray(fl));
assert(fl.length === 0);
assert.deepEqual(e._events, {});
assert.ok(Array.isArray(fl));
assert.strictEqual(fl.length, 0);
if (Object.create) assert.ok(!(e._events instanceof Object));
assert.strictEqual(objectKeys(e._events).length, 0);
e.on('foo', assert.fail);
fl = e.listeners('foo');
assert(e._events.foo === assert.fail);
assert(Array.isArray(fl));
assert(fl.length === 1);
assert(fl[0] === assert.fail);
assert.strictEqual(e._events.foo, assert.fail);
assert.ok(Array.isArray(fl));
assert.strictEqual(fl.length, 1);
assert.strictEqual(fl[0], assert.fail);
e.listeners('bar');
assert(!e._events.hasOwnProperty('bar'));

@@ -48,10 +50,10 @@ e.on('foo', assert.ok);

assert(Array.isArray(e._events.foo));
assert(e._events.foo.length === 2);
assert(e._events.foo[0] === assert.fail);
assert(e._events.foo[1] === assert.ok);
assert.ok(Array.isArray(e._events.foo));
assert.strictEqual(e._events.foo.length, 2);
assert.strictEqual(e._events.foo[0], assert.fail);
assert.strictEqual(e._events.foo[1], assert.ok);
assert(Array.isArray(fl));
assert(fl.length === 2);
assert(fl[0] === assert.fail);
assert(fl[1] === assert.ok);
assert.ok(Array.isArray(fl));
assert.strictEqual(fl.length, 2);
assert.strictEqual(fl[0], assert.fail);
assert.strictEqual(fl[1], assert.ok);

@@ -1,2 +0,1 @@

// Copyright Joyent, Inc. and other Node contributors.

@@ -23,30 +22,109 @@ //

require('./common');
var assert = require('assert');
var events = require('../');
var util = require('util');
function listener() {}
function listener2() {}
var listener = function listener() {};
var listener2 = function listener2() {};
function TestStream() {}
util.inherits(TestStream, events.EventEmitter);
var e1 = new events.EventEmitter();
e1.on('foo', listener);
var fooListeners = e1.listeners('foo');
assert.deepEqual(e1.listeners('foo'), [listener]);
e1.removeAllListeners('foo');
assert.deepEqual(e1.listeners('foo'), []);
assert.deepEqual(fooListeners, [listener]);
{
var ee = new events.EventEmitter();
ee.on('foo', listener);
var fooListeners = ee.listeners('foo');
var e2 = new events.EventEmitter();
e2.on('foo', listener);
var e2ListenersCopy = e2.listeners('foo');
assert.deepEqual(e2ListenersCopy, [listener]);
assert.deepEqual(e2.listeners('foo'), [listener]);
e2ListenersCopy.push(listener2);
assert.deepEqual(e2.listeners('foo'), [listener]);
assert.deepEqual(e2ListenersCopy, [listener, listener2]);
var listeners = ee.listeners('foo');
assert.ok(Array.isArray(listeners));
assert.strictEqual(listeners.length, 1);
assert.strictEqual(listeners[0], listener);
var e3 = new events.EventEmitter();
e3.on('foo', listener);
var e3ListenersCopy = e3.listeners('foo');
e3.on('foo', listener2);
assert.deepEqual(e3.listeners('foo'), [listener, listener2]);
assert.deepEqual(e3ListenersCopy, [listener]);
ee.removeAllListeners('foo');
listeners = ee.listeners('foo');
assert.ok(Array.isArray(listeners));
assert.strictEqual(listeners.length, 0);
assert.ok(Array.isArray(fooListeners));
assert.strictEqual(fooListeners.length, 1);
assert.strictEqual(fooListeners[0], listener);
}
{
var ee = new events.EventEmitter();
ee.on('foo', listener);
var eeListenersCopy = ee.listeners('foo');
assert.ok(Array.isArray(eeListenersCopy));
assert.strictEqual(eeListenersCopy.length, 1);
assert.strictEqual(eeListenersCopy[0], listener);
var listeners = ee.listeners('foo');
assert.ok(Array.isArray(listeners));
assert.strictEqual(listeners.length, 1);
assert.strictEqual(listeners[0], listener);
eeListenersCopy.push(listener2);
listeners = ee.listeners('foo');
assert.ok(Array.isArray(listeners));
assert.strictEqual(listeners.length, 1);
assert.strictEqual(listeners[0], listener);
assert.strictEqual(eeListenersCopy.length, 2);
assert.strictEqual(eeListenersCopy[0], listener);
assert.strictEqual(eeListenersCopy[1], listener2);
}
{
var ee = new events.EventEmitter();
ee.on('foo', listener);
var eeListenersCopy = ee.listeners('foo');
ee.on('foo', listener2);
var listeners = ee.listeners('foo');
assert.ok(Array.isArray(listeners));
assert.strictEqual(listeners.length, 2);
assert.strictEqual(listeners[0], listener);
assert.strictEqual(listeners[1], listener2);
assert.ok(Array.isArray(eeListenersCopy));
assert.strictEqual(eeListenersCopy.length, 1);
assert.strictEqual(eeListenersCopy[0], listener);
}
{
var ee = new events.EventEmitter();
ee.once('foo', listener);
var listeners = ee.listeners('foo');
assert.ok(Array.isArray(listeners));
assert.strictEqual(listeners.length, 1);
assert.strictEqual(listeners[0], listener);
}
{
var ee = new events.EventEmitter();
ee.on('foo', listener);
ee.once('foo', listener2);
var listeners = ee.listeners('foo');
assert.ok(Array.isArray(listeners));
assert.strictEqual(listeners.length, 2);
assert.strictEqual(listeners[0], listener);
assert.strictEqual(listeners[1], listener2);
}
{
var ee = new events.EventEmitter();
ee._events = undefined;
var listeners = ee.listeners('foo');
assert.ok(Array.isArray(listeners));
assert.strictEqual(listeners.length, 0);
}
{
var s = new TestStream();
var listeners = s.listeners('foo');
assert.ok(Array.isArray(listeners));
assert.strictEqual(listeners.length, 0);
}

@@ -22,30 +22,27 @@ // Copyright Joyent, Inc. and other Node contributors.

var common = require('./common');
var assert = require('assert');
var events = require('../');
var e = new events.EventEmitter();
var gotEvent = false;
var hasDefineProperty = !!Object.defineProperty;
try { Object.defineProperty({}, 'x', { value: 0 }); } catch (err) { hasDefineProperty = false }
var e = new events.EventEmitter();
e.on('maxListeners', common.mustCall());
e.on('maxListeners', function() {
gotEvent = true;
});
// Should not corrupt the 'maxListeners' queue.
e.setMaxListeners(42);
assert.throws(function() {
e.setMaxListeners(NaN);
});
var throwsObjs = [NaN, -1, 'and even this'];
var maxError = /^TypeError: "n" argument must be a positive number$/;
var defError = /^TypeError: "defaultMaxListeners" must be a positive number$/;
assert.throws(function() {
e.setMaxListeners(-1);
});
for (var i = 0; i < throwsObjs.length; i++) {
var obj = throwsObjs[i];
assert.throws(function() { e.setMaxListeners(obj); }, maxError);
if (hasDefineProperty) {
assert.throws(function() { events.defaultMaxListeners = obj; }, defError);
}
}
assert.throws(function() {
e.setMaxListeners("and even this");
});
e.emit('maxListeners');
assert(gotEvent);

@@ -22,2 +22,3 @@ // Copyright Joyent, Inc. and other Node contributors.

require('./common');
var assert = require('assert');

@@ -48,21 +49,31 @@ var events = require('../');

e.on('foo', callback1);
assert.equal(1, e.listeners('foo').length);
assert.strictEqual(e.listeners('foo').length, 1);
e.emit('foo');
assert.equal(2, e.listeners('foo').length);
assert.deepEqual(['callback1'], callbacks_called);
assert.strictEqual(e.listeners('foo').length, 2);
assert.ok(Array.isArray(callbacks_called));
assert.strictEqual(callbacks_called.length, 1);
assert.strictEqual(callbacks_called[0], 'callback1');
e.emit('foo');
assert.equal(0, e.listeners('foo').length);
assert.deepEqual(['callback1', 'callback2', 'callback3'], callbacks_called);
assert.strictEqual(e.listeners('foo').length, 0);
assert.ok(Array.isArray(callbacks_called));
assert.strictEqual(callbacks_called.length, 3);
assert.strictEqual(callbacks_called[0], 'callback1');
assert.strictEqual(callbacks_called[1], 'callback2');
assert.strictEqual(callbacks_called[2], 'callback3');
e.emit('foo');
assert.equal(0, e.listeners('foo').length);
assert.deepEqual(['callback1', 'callback2', 'callback3'], callbacks_called);
assert.strictEqual(e.listeners('foo').length, 0);
assert.ok(Array.isArray(callbacks_called));
assert.strictEqual(callbacks_called.length, 3);
assert.strictEqual(callbacks_called[0], 'callback1');
assert.strictEqual(callbacks_called[1], 'callback2');
assert.strictEqual(callbacks_called[2], 'callback3');
e.on('foo', callback1);
e.on('foo', callback2);
assert.equal(2, e.listeners('foo').length);
assert.strictEqual(e.listeners('foo').length, 2);
e.removeAllListeners('foo');
assert.equal(0, e.listeners('foo').length);
assert.strictEqual(e.listeners('foo').length, 0);

@@ -75,5 +86,8 @@ // Verify that removing callbacks while in emit allows emits to propagate to

e.on('foo', callback3);
assert.equal(2, e.listeners('foo').length);
assert.strictEqual(2, e.listeners('foo').length);
e.emit('foo');
assert.deepEqual(['callback2', 'callback3'], callbacks_called);
assert.equal(0, e.listeners('foo').length);
assert.ok(Array.isArray(callbacks_called));
assert.strictEqual(callbacks_called.length, 2);
assert.strictEqual(callbacks_called[0], 'callback2');
assert.strictEqual(callbacks_called[1], 'callback3');
assert.strictEqual(0, e.listeners('foo').length);

@@ -22,16 +22,29 @@ // Copyright Joyent, Inc. and other Node contributors.

require('./common');
var assert = require('assert');
var events = require('../');
var e = new events.EventEmitter(),
num_args_emited = [];
var after_checks = [];
after(function() {
for (var i = 0 ; i < after_checks.length ; ++i) {
after_checks[i]();
}
});
var e = new events.EventEmitter();
var num_args_emitted = [];
e.on('numArgs', function() {
var numArgs = arguments.length;
console.log('numArgs: ' + numArgs);
num_args_emited.push(numArgs);
num_args_emitted.push(numArgs);
});
console.log('start');
e.on('foo', function() {
num_args_emitted.push(arguments.length);
});
e.on('foo', function() {
num_args_emitted.push(arguments.length);
});
e.emit('numArgs');

@@ -44,3 +57,15 @@ e.emit('numArgs', null);

assert.deepEqual([0, 1, 2, 3, 4, 5], num_args_emited);
e.emit('foo', null, null, null, null);
after_checks.push(function() {
assert.ok(Array.isArray(num_args_emitted));
assert.strictEqual(num_args_emitted.length, 8);
assert.strictEqual(num_args_emitted[0], 0);
assert.strictEqual(num_args_emitted[1], 1);
assert.strictEqual(num_args_emitted[2], 2);
assert.strictEqual(num_args_emitted[3], 3);
assert.strictEqual(num_args_emitted[4], 4);
assert.strictEqual(num_args_emitted[5], 5);
assert.strictEqual(num_args_emitted[6], 4);
assert.strictEqual(num_args_emitted[6], 4);
});

@@ -22,11 +22,9 @@ // Copyright Joyent, Inc. and other Node contributors.

var common = require('./common');
var assert = require('assert');
var events = require('../');
var EventEmitter = require('../');
var e = new events.EventEmitter();
var times_hello_emited = 0;
var e = new EventEmitter();
e.once('hello', function(a, b) {
times_hello_emited++;
});
e.once('hello', common.mustCall());

@@ -38,5 +36,5 @@ e.emit('hello', 'a', 'b');

var remove = function() {
assert.fail(1, 0, 'once->foo should not be emitted', '!');
};
function remove() {
assert.fail('once->foo should not be emitted');
}

@@ -47,16 +45,42 @@ e.once('foo', remove);

var times_recurse_emitted = 0;
e.once('e', common.mustCall(function() {
e.emit('e');
}));
e.once('e', function() {
e.emit('e');
times_recurse_emitted++;
});
e.once('e', common.mustCall());
e.once('e', function() {
times_recurse_emitted++;
});
e.emit('e');
assert.equal(1, times_hello_emited);
assert.equal(2, times_recurse_emitted);
// Verify that the listener must be a function
assert.throws(function() {
var ee = new EventEmitter();
ee.once('foo', null);
}, /^TypeError: "listener" argument must be a function$/);
{
// once() has different code paths based on the number of arguments being
// emitted. Verify that all of the cases are covered.
var maxArgs = 4;
for (var i = 0; i <= maxArgs; ++i) {
var ee = new EventEmitter();
var args = ['foo'];
for (var j = 0; j < i; ++j)
args.push(j);
ee.once('foo', common.mustCall(function() {
var params = Array.prototype.slice.call(arguments);
var restArgs = args.slice(1);
assert.ok(Array.isArray(params));
assert.strictEqual(params.length, restArgs.length);
for (var index = 0; index < params.length; index++) {
var param = params[index];
assert.strictEqual(param, restArgs[index]);
}
}));
EventEmitter.prototype.emit.apply(ee, args);
}
}

@@ -28,3 +28,3 @@ // Copyright Joyent, Inc. and other Node contributors.

after(function() {
for (var i=0 ; i<after_checks.length ; ++i) {
for (var i = 0 ; i < after_checks.length ; ++i) {
after_checks[i]();

@@ -37,7 +37,12 @@ }

after_checks.push(function() {
assert.deepEqual(actual.sort(), expected.sort());
var sortedActual = actual.sort();
var sortedExpected = expected.sort();
assert.strictEqual(sortedActual.length, sortedExpected.length);
for (var index = 0; index < sortedActual.length; index++) {
var value = sortedActual[index];
assert.strictEqual(value, sortedExpected[index]);
}
});
function listener(name) {
actual.push(name)
actual.push(name);
}

@@ -47,37 +52,91 @@ return common.mustCall(listener, expected.length);

function listener() {}
{
var ee = new events.EventEmitter();
var noop = common.mustNotCall();
ee.on('foo', noop);
ee.on('bar', noop);
ee.on('baz', noop);
ee.on('baz', noop);
var fooListeners = ee.listeners('foo');
var barListeners = ee.listeners('bar');
var bazListeners = ee.listeners('baz');
ee.on('removeListener', expect(['bar', 'baz', 'baz']));
ee.removeAllListeners('bar');
ee.removeAllListeners('baz');
var e1 = new events.EventEmitter();
e1.on('foo', listener);
e1.on('bar', listener);
e1.on('baz', listener);
e1.on('baz', listener);
var fooListeners = e1.listeners('foo');
var barListeners = e1.listeners('bar');
var bazListeners = e1.listeners('baz');
e1.on('removeListener', expect(['bar', 'baz', 'baz']));
e1.removeAllListeners('bar');
e1.removeAllListeners('baz');
assert.deepEqual(e1.listeners('foo'), [listener]);
assert.deepEqual(e1.listeners('bar'), []);
assert.deepEqual(e1.listeners('baz'), []);
// after calling removeAllListeners,
// the old listeners array should stay unchanged
assert.deepEqual(fooListeners, [listener]);
assert.deepEqual(barListeners, [listener]);
assert.deepEqual(bazListeners, [listener, listener]);
// after calling removeAllListeners,
// new listeners arrays are different from the old
assert.notEqual(e1.listeners('bar'), barListeners);
assert.notEqual(e1.listeners('baz'), bazListeners);
var listeners = ee.listeners('foo');
assert.ok(Array.isArray(listeners));
assert.strictEqual(listeners.length, 1);
assert.strictEqual(listeners[0], noop);
var e2 = new events.EventEmitter();
e2.on('foo', listener);
e2.on('bar', listener);
// expect LIFO order
e2.on('removeListener', expect(['foo', 'bar', 'removeListener']));
e2.on('removeListener', expect(['foo', 'bar']));
e2.removeAllListeners();
console.error(e2);
assert.deepEqual([], e2.listeners('foo'));
assert.deepEqual([], e2.listeners('bar'));
listeners = ee.listeners('bar');
assert.ok(Array.isArray(listeners));
assert.strictEqual(listeners.length, 0);
listeners = ee.listeners('baz');
assert.ok(Array.isArray(listeners));
assert.strictEqual(listeners.length, 0);
// After calling removeAllListeners(),
// the old listeners array should stay unchanged.
assert.strictEqual(fooListeners.length, 1);
assert.strictEqual(fooListeners[0], noop);
assert.strictEqual(barListeners.length, 1);
assert.strictEqual(barListeners[0], noop);
assert.strictEqual(bazListeners.length, 2);
assert.strictEqual(bazListeners[0], noop);
assert.strictEqual(bazListeners[1], noop);
// After calling removeAllListeners(),
// new listeners arrays is different from the old.
assert.notStrictEqual(ee.listeners('bar'), barListeners);
assert.notStrictEqual(ee.listeners('baz'), bazListeners);
}
{
var ee = new events.EventEmitter();
ee.on('foo', common.mustNotCall());
ee.on('bar', common.mustNotCall());
// Expect LIFO order
ee.on('removeListener', expect(['foo', 'bar', 'removeListener']));
ee.on('removeListener', expect(['foo', 'bar']));
ee.removeAllListeners();
var listeners = ee.listeners('foo');
assert.ok(Array.isArray(listeners));
assert.strictEqual(listeners.length, 0);
listeners = ee.listeners('bar');
assert.ok(Array.isArray(listeners));
assert.strictEqual(listeners.length, 0);
}
{
var ee = new events.EventEmitter();
ee.on('removeListener', common.mustNotCall());
// Check for regression where removeAllListeners() throws when
// there exists a 'removeListener' listener, but there exists
// no listeners for the provided event type.
assert.doesNotThrow(function () { ee.removeAllListeners(ee, 'foo') });
}
{
var ee = new events.EventEmitter();
var expectLength = 2;
ee.on('removeListener', function() {
assert.strictEqual(expectLength--, this.listeners('baz').length);
});
ee.on('baz', common.mustNotCall());
ee.on('baz', common.mustNotCall());
ee.on('baz', common.mustNotCall());
assert.strictEqual(ee.listeners('baz').length, expectLength + 1);
ee.removeAllListeners('baz');
assert.strictEqual(ee.listeners('baz').length, 0);
}
{
var ee = new events.EventEmitter();
assert.strictEqual(ee, ee.removeAllListeners());
}
{
var ee = new events.EventEmitter();
ee._events = undefined;
assert.strictEqual(ee, ee.removeAllListeners());
}

@@ -24,62 +24,190 @@ // Copyright Joyent, Inc. and other Node contributors.

var assert = require('assert');
var events = require('../');
var EventEmitter = require('../');
var count = 0;
var listener1 = function listener1() {};
var listener2 = function listener2() {};
function listener1() {
console.log('listener1');
count++;
{
var ee = new EventEmitter();
ee.on('hello', listener1);
ee.on('removeListener', common.mustCall(function(name, cb) {
assert.strictEqual(name, 'hello');
assert.strictEqual(cb, listener1);
}));
ee.removeListener('hello', listener1);
var listeners = ee.listeners('hello');
assert.ok(Array.isArray(listeners));
assert.strictEqual(listeners.length, 0);
}
function listener2() {
console.log('listener2');
count++;
{
var ee = new EventEmitter();
ee.on('hello', listener1);
ee.on('removeListener', common.mustNotCall());
ee.removeListener('hello', listener2);
var listeners = ee.listeners('hello');
assert.ok(Array.isArray(listeners));
assert.strictEqual(listeners.length, 1);
assert.strictEqual(listeners[0], listener1);
}
function listener3() {
console.log('listener3');
count++;
{
var ee = new EventEmitter();
ee.on('hello', listener1);
ee.on('hello', listener2);
var listeners;
ee.once('removeListener', common.mustCall(function(name, cb) {
assert.strictEqual(name, 'hello');
assert.strictEqual(cb, listener1);
listeners = ee.listeners('hello');
assert.ok(Array.isArray(listeners));
assert.strictEqual(listeners.length, 1);
assert.strictEqual(listeners[0], listener2);
}));
ee.removeListener('hello', listener1);
listeners = ee.listeners('hello');
assert.ok(Array.isArray(listeners));
assert.strictEqual(listeners.length, 1);
assert.strictEqual(listeners[0], listener2);
ee.once('removeListener', common.mustCall(function(name, cb) {
assert.strictEqual(name, 'hello');
assert.strictEqual(cb, listener2);
listeners = ee.listeners('hello');
assert.ok(Array.isArray(listeners));
assert.strictEqual(listeners.length, 0);
}));
ee.removeListener('hello', listener2);
listeners = ee.listeners('hello');
assert.ok(Array.isArray(listeners));
assert.strictEqual(listeners.length, 0);
}
function remove1() {
assert(0);
{
var ee = new EventEmitter();
function remove1() {
assert.fail('remove1 should not have been called');
}
function remove2() {
assert.fail('remove2 should not have been called');
}
ee.on('removeListener', common.mustCall(function(name, cb) {
if (cb !== remove1) return;
this.removeListener('quux', remove2);
this.emit('quux');
}, 2));
ee.on('quux', remove1);
ee.on('quux', remove2);
ee.removeListener('quux', remove1);
}
function remove2() {
assert(0);
{
var ee = new EventEmitter();
ee.on('hello', listener1);
ee.on('hello', listener2);
var listeners;
ee.once('removeListener', common.mustCall(function(name, cb) {
assert.strictEqual(name, 'hello');
assert.strictEqual(cb, listener1);
listeners = ee.listeners('hello');
assert.ok(Array.isArray(listeners));
assert.strictEqual(listeners.length, 1);
assert.strictEqual(listeners[0], listener2);
ee.once('removeListener', common.mustCall(function(name, cb) {
assert.strictEqual(name, 'hello');
assert.strictEqual(cb, listener2);
listeners = ee.listeners('hello');
assert.ok(Array.isArray(listeners));
assert.strictEqual(listeners.length, 0);
}));
ee.removeListener('hello', listener2);
listeners = ee.listeners('hello');
assert.ok(Array.isArray(listeners));
assert.strictEqual(listeners.length, 0);
}));
ee.removeListener('hello', listener1);
listeners = ee.listeners('hello');
assert.ok(Array.isArray(listeners));
assert.strictEqual(listeners.length, 0);
}
var e1 = new events.EventEmitter();
e1.on('hello', listener1);
e1.on('removeListener', common.mustCall(function(name, cb) {
assert.equal(name, 'hello');
assert.equal(cb, listener1);
}));
e1.removeListener('hello', listener1);
assert.deepEqual([], e1.listeners('hello'));
{
var ee = new EventEmitter();
var listener3 = common.mustCall(function() {
ee.removeListener('hello', listener4);
}, 2);
var listener4 = common.mustCall();
var e2 = new events.EventEmitter();
e2.on('hello', listener1);
e2.on('removeListener', assert.fail);
e2.removeListener('hello', listener2);
assert.deepEqual([listener1], e2.listeners('hello'));
ee.on('hello', listener3);
ee.on('hello', listener4);
var e3 = new events.EventEmitter();
e3.on('hello', listener1);
e3.on('hello', listener2);
e3.on('removeListener', common.mustCall(function(name, cb) {
assert.equal(name, 'hello');
assert.equal(cb, listener1);
}));
e3.removeListener('hello', listener1);
assert.deepEqual([listener2], e3.listeners('hello'));
// listener4 will still be called although it is removed by listener 3.
ee.emit('hello');
// This is so because the interal listener array at time of emit
// was [listener3,listener4]
var e4 = new events.EventEmitter();
e4.on('removeListener', common.mustCall(function(name, cb) {
if (cb !== remove1) return;
this.removeListener('quux', remove2);
this.emit('quux');
}, 2));
e4.on('quux', remove1);
e4.on('quux', remove2);
e4.removeListener('quux', remove1);
// Interal listener array [listener3]
ee.emit('hello');
}
{
var ee = new EventEmitter();
ee.once('hello', listener1);
ee.on('removeListener', common.mustCall(function(eventName, listener) {
assert.strictEqual(eventName, 'hello');
assert.strictEqual(listener, listener1);
}));
ee.emit('hello');
}
{
var ee = new EventEmitter();
assert.strictEqual(ee, ee.removeListener('foo', function() {}));
}
// Verify that the removed listener must be a function
assert.throws(function() {
var ee = new EventEmitter();
ee.removeListener('foo', null);
}, /^TypeError: "listener" argument must be a function$/);
{
var ee = new EventEmitter();
var listener = function() {};
ee._events = undefined;
var e = ee.removeListener('foo', listener);
assert.strictEqual(e, ee);
}
{
var ee = new EventEmitter();
ee.on('foo', listener1);
ee.on('foo', listener2);
var listeners = ee.listeners('foo');
assert.ok(Array.isArray(listeners));
assert.strictEqual(listeners.length, 2);
assert.strictEqual(listeners[0], listener1);
assert.strictEqual(listeners[1], listener2);
ee.removeListener('foo', listener1);
assert.strictEqual(ee._events.foo, listener2);
ee.on('foo', listener1);
listeners = ee.listeners('foo');
assert.ok(Array.isArray(listeners));
assert.strictEqual(listeners.length, 2);
assert.strictEqual(listeners[0], listener2);
assert.strictEqual(listeners[1], listener1);
ee.removeListener('foo', listener1);
assert.strictEqual(ee._events.foo, listener2);
}

@@ -22,9 +22,12 @@ // Copyright Joyent, Inc. and other Node contributors.

require('./common');
var assert = require('assert');
var events = require('../');
var objectKeys = require('object-keys');
var e = new events.EventEmitter;
var e = new events.EventEmitter();
assert.deepEqual(e._events, {});
if (Object.create) assert.ok(!(e._events instanceof Object));
assert.strictEqual(objectKeys(e._events).length, 0);
e.setMaxListeners(5);
assert.deepEqual(e._events, {});
assert.strictEqual(objectKeys(e._events).length, 0);

@@ -22,6 +22,15 @@ // Copyright Joyent, Inc. and other Node contributors.

var common = require('./common');
var assert = require('assert');
var EventEmitter = require('../').EventEmitter;
var util = require('util');
var objectKeys = require('object-keys');
var after_checks = [];
after(function() {
for (var i = 0 ; i < after_checks.length ; ++i) {
after_checks[i]();
}
});
util.inherits(MyEE, EventEmitter);

@@ -36,6 +45,3 @@

var called = false;
var myee = new MyEE(function() {
called = true;
});
var myee = new MyEE(common.mustCall());

@@ -52,3 +58,19 @@

assert(called);
assert.deepEqual(myee._events, {});
after_checks.push(function() {
if (Object.create) assert.ok(!(myee._events instanceof Object));
assert.strictEqual(objectKeys(myee._events).length, 0);
});
function MyEE2() {
EventEmitter.call(this);
}
MyEE2.prototype = new EventEmitter();
var ee1 = new MyEE2();
var ee2 = new MyEE2();
ee1.on('x', function() {});
assert.strictEqual(ee2.listenerCount('x'), 0);

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc