function EventEmitter(conf) { this._events = {}; this.newListener = false; this.verboseMemoryLeak = false; configure.call(this, conf); }
n/a
function EventEmitter(conf) { this._events = {}; this.newListener = false; this.verboseMemoryLeak = false; configure.call(this, conf); }
n/a
function EventEmitter(conf) { this._events = {}; this.newListener = false; this.verboseMemoryLeak = false; configure.call(this, conf); }
n/a
_many = function (event, ttl, fn, prepend) { var self = this; if (typeof fn !== 'function') { throw new Error('many only accepts instances of Function'); } function listener() { if (--ttl === 0) { self.off(event, listener); } return fn.apply(this, arguments); } listener._origin = fn; this._on(event, listener, prepend); return self; }
n/a
_on = function (type, listener, prepend) { if (typeof type === 'function') { this._onAny(type, listener); return this; } if (typeof listener !== 'function') { throw new Error('on only accepts instances of Function'); } this._events || init.call(this); // To avoid recursion in the case that type == "newListeners"! Before // adding it to the listeners, first emit "newListeners". this.emit('newListener', type, listener); if (this.wildcard) { growListenerTree.call(this, type, listener); return this; } if (!this._events[type]) { // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; } else { if (typeof this._events[type] === 'function') { // Change to array. this._events[type] = [this._events[type]]; } // If we've already got an array, just add if(prepend){ this._events[type].unshift(listener); }else{ this._events[type].push(listener); } // Check for listener leak if ( !this._events[type].warned && this._maxListeners > 0 && this._events[type].length > this._maxListeners ) { this._events[type].warned = true; logPossibleMemoryLeak.call(this, this._events[type].length, type); } } return this; }
n/a
_onAny = function (fn, prepend){ if (typeof fn !== 'function') { throw new Error('onAny only accepts instances of Function'); } if (!this._all) { this._all = []; } // Add the function to the event listener collection. if(prepend){ this._all.unshift(fn); }else{ this._all.push(fn); } return this; }
n/a
_once = function (event, fn, prepend) { this._many(event, 1, fn, prepend); return this; }
n/a
addListener = function (type, listener) { return this._on(type, listener, false); }
...
emitter.emit('foo.bar');
emitter.emit('foo.bar.baz');
````
On the other hand, if the single-wildcard event name was passed to the on method, the callback would only observe the second of
these events.
### emitter.addListener(event, listener)
### emitter.on(event, listener)
Adds a listener to the end of the listeners array for the specified event.
```javascript
server.on('data', function(value1, value2, value3, ...) {
console.log('The event was raised!');
...
emit = function () { this._events || init.call(this); var type = arguments[0]; if (type === 'newListener' && !this.newListener) { if (!this._events.newListener) { return false; } } var al = arguments.length; var args,l,i,j; var handler; if (this._all && this._all.length) { handler = this._all.slice(); if (al > 3) { args = new Array(al); for (j = 0; j < al; j++) args[j] = arguments[j]; } for (i = 0, l = handler.length; i < l; i++) { this.event = type; switch (al) { case 1: handler[i].call(this, type); break; case 2: handler[i].call(this, type, arguments[1]); break; case 3: handler[i].call(this, type, arguments[1], arguments[2]); break; default: handler[i].apply(this, args); } } } if (this.wildcard) { handler = []; var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); searchListenerTree.call(this, handler, ns, this.listenerTree, 0); } else { handler = this._events[type]; if (typeof handler === 'function') { this.event = type; switch (al) { case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; default: args = new Array(al - 1); for (j = 1; j < al; j++) args[j - 1] = arguments[j]; handler.apply(this, args); } return true; } else if (handler) { // need to make copy of handlers because list can change in the middle // of emit call handler = handler.slice(); } } if (handler && handler.length) { if (al > 3) { args = new Array(al - 1); for (j = 1; j < al; j++) args[j - 1] = arguments[j]; } for (i = 0, l = handler.length; i < l; i++) { this.event = type; switch (al) { case 1: handler[i].call(this); break; case 2: handler[i].call(this, arguments[1]); break; case 3: handler[i].call(this, arguments[1], arguments[2]); break; default: handler[i].apply(this, args); } } return true; } else if (!this._all && type === 'error') { if (arguments[1] instanceof Error) { throw arguments[1]; // Unhandled 'error' event } else { throw new Error("Uncaught, unspecified 'error' event."); } return false; } return !!this._all; }
...
`*` character). If the event name is a string, a wildcard may appear as `foo.*`.
If the event name is an array, the wildcard may appear as `['foo', '*']`.
If either of the above described events were passed to the `on` method,
subsequent emits such as the following would be observed...
```javascript
emitter.emit('foo.bazz');
emitter.emit(['foo', 'bar']);
```
# Multi-level Wildcards
A double wildcard (the string `**`) matches any number of levels (zero or more) of events. So if for example `'foo.**'`
is passed to the `on` method, the following events would be observed:
````javascript
...
emitAsync = function () { this._events || init.call(this); var type = arguments[0]; if (type === 'newListener' && !this.newListener) { if (!this._events.newListener) { return Promise.resolve([false]); } } var promises= []; var al = arguments.length; var args,l,i,j; var handler; if (this._all) { if (al > 3) { args = new Array(al); for (j = 1; j < al; j++) args[j] = arguments[j]; } for (i = 0, l = this._all.length; i < l; i++) { this.event = type; switch (al) { case 1: promises.push(this._all[i].call(this, type)); break; case 2: promises.push(this._all[i].call(this, type, arguments[1])); break; case 3: promises.push(this._all[i].call(this, type, arguments[1], arguments[2])); break; default: promises.push(this._all[i].apply(this, args)); } } } if (this.wildcard) { handler = []; var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); searchListenerTree.call(this, handler, ns, this.listenerTree, 0); } else { handler = this._events[type]; } if (typeof handler === 'function') { this.event = type; switch (al) { case 1: promises.push(handler.call(this)); break; case 2: promises.push(handler.call(this, arguments[1])); break; case 3: promises.push(handler.call(this, arguments[1], arguments[2])); break; default: args = new Array(al - 1); for (j = 1; j < al; j++) args[j - 1] = arguments[j]; promises.push(handler.apply(this, args)); } } else if (handler && handler.length) { handler = handler.slice(); if (al > 3) { args = new Array(al - 1); for (j = 1; j < al; j++) args[j - 1] = arguments[j]; } for (i = 0, l = handler.length; i < l; i++) { this.event = type; switch (al) { case 1: promises.push(handler[i].call(this)); break; case 2: promises.push(handler[i].call(this, arguments[1])); break; case 3: promises.push(handler[i].call(this, arguments[1], arguments[2])); break; default: promises.push(handler[i].apply(this, args)); } } } else if (!this._all && type === 'error') { if (arguments[1] instanceof Error) { return Promise.reject(arguments[1]); // Unhandled 'error' event } else { return Promise.reject("Uncaught, unspecified 'error' event."); } } return Promise.all(promises); }
...
```
### emitter.emit(event, [arg1], [arg2], [...])
Execute each of the listeners that may be listening for the specified event
name in order with the list of arguments.
### emitter.emitAsync(event, [arg1], [arg2], [...])
Return the results of the listeners via [Promise.all](https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects
/Promise/all).
Only this method doesn't work [IE](http://caniuse.com/#search=promise).
```javascript
emitter.on('get',function(i) {
return new Promise(function(resolve){
...
eventNames = function (){ return Object.keys(this._events); }
...
emitter.emitAsync('get',0)
.then(function(results){
console.log(results); // [3,2,1,0,undefined]
});
```
### emitter.eventNames()
Returns an array listing the events for which the emitter has registered listeners. The values in the array will be strings.
```javascript
emitter.on('foo', () => {});
emitter.on('bar', () => {});
...
listenerCount = function (type) { return this.listeners(type).length; }
n/a
listeners = function (type) { if (this.wildcard) { var handlers = []; var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); searchListenerTree.call(this, handlers, ns, this.listenerTree, 0); return handlers; } this._events || init.call(this); if (!this._events[type]) this._events[type] = []; if (!isArray(this._events[type])) { this._events[type] = [this._events[type]]; } return this._events[type]; }
...
By default EventEmitters will print a warning if more than 10 listeners
are added to it. This is a useful default which helps finding memory leaks.
Obviously not all Emitters should be limited to 10. This function allows
that to be increased. Set to zero for unlimited.
### emitter.listeners(event)
Returns an array of listeners for the specified event. This array can be
manipulated, e.g. to remove listeners.
```javascript
server.on('get', function(value) {
console.log('someone connected!');
...
listenersAny = function () { if(this._all) { return this._all; } else { return []; } }
...
```javascript
server.on('get', function(value) {
console.log('someone connected!');
});
console.log(server.listeners('get')); // [ [Function] ]
```
### emitter.listenersAny()
Returns an array of listeners that are listening for any event that is
specified. This array can be manipulated, e.g. to remove listeners.
```javascript
server.onAny(function(value) {
console.log('someone connected!');
...
many = function (event, ttl, fn) { return this._many(event, ttl, fn, false); }
...
console.log(this.event, value1, value2);
});
```
- Fire an event N times and then remove it, an extension of the `once` concept.
```javascript
server.many('foo', 4, function() {
console.log('hello');
});
```
- Pass in a namespaced event as an array rather than a delimited string.
```javascript
...
off = function (type, listener) { if (typeof listener !== 'function') { throw new Error('removeListener only takes instances of Function'); } var handlers,leafs=[]; if(this.wildcard) { var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0); } else { // does not use listeners(), so no side effect of creating _events[type] if (!this._events[type]) return this; handlers = this._events[type]; leafs.push({_listeners:handlers}); } for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) { var leaf = leafs[iLeaf]; handlers = leaf._listeners; if (isArray(handlers)) { var position = -1; for (var i = 0, length = handlers.length; i < length; i++) { if (handlers[i] === listener || (handlers[i].listener && handlers[i].listener === listener) || (handlers[i]._origin && handlers[i]._origin === listener)) { position = i; break; } } if (position < 0) { continue; } if(this.wildcard) { leaf._listeners.splice(position, 1); } else { this._events[type].splice(position, 1); } if (handlers.length === 0) { if(this.wildcard) { delete leaf._listeners; } else { delete this._events[type]; } } this.emit("removeListener", type, listener); return this; } else if (handlers === listener || (handlers.listener && handlers.listener === listener) || (handlers._origin && handlers._origin === listener)) { if(this.wildcard) { delete leaf._listeners; } else { delete this._events[type]; } this.emit("removeListener", type, listener); } } function recursivelyGarbageCollect(root) { if (root === undefined) { return; } var keys = Object.keys(root); for (var i in keys) { var key = keys[i]; var obj = root[key]; if ((obj instanceof Function) || (typeof obj !== "object") || (obj === null)) continue; if (Object.keys(obj).length > 0) { recursivelyGarbageCollect(root[key]); } if (Object.keys(obj).length === 0) { delete root[key]; } } } recursivelyGarbageCollect(this.listenerTree); return this; }
...
console.log('This event will be listened to exactly four times.');
});
```
### emitter.removeListener(event, listener)
### emitter.off(event, listener)
Remove a listener from the listener array for the specified event.
**Caution**: Calling this method changes the array indices in the listener array behind the listener.
```javascript
var callback = function(value) {
console.log('someone connected!');
...
offAny = function (fn) { var i = 0, l = 0, fns; if (fn && this._all && this._all.length > 0) { fns = this._all; for(i = 0, l = fns.length; i < l; i++) { if(fn === fns[i]) { fns.splice(i, 1); this.emit("removeListenerAny", fn); return this; } } } else { fns = this._all; for(i = 0, l = fns.length; i < l; i++) this.emit("removeListenerAny", fns[i]); this._all = []; } return this; }
...
```javascript
server.prependAny(function(event, value) {
console.log('All events trigger this.');
});
```
### emitter.offAny(listener)
Removes the listener that will be fired when any event is emitted.
```javascript
server.offAny(function(value) {
console.log('The event was raised!');
});
...
on = function (type, listener) { return this._on(type, listener, false); }
...
verboseMemoryLeak: false
});
```
- Getting the actual event that fired.
```javascript
server.on('foo.*', function(value1, value2) {
console.log(this.event, value1, value2);
});
```
- Fire an event N times and then remove it, an extension of the `once` concept.
```javascript
...
onAny = function (fn) { return this._onAny(fn, false); }
...
```javascript
server.prependListener('data', function(value1, value2, value3, ...) {
console.log('The event was raised!');
});
```
### emitter.onAny(listener)
Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the callback.
```javascript
server.onAny(function(event, value) {
console.log('All events trigger this.');
});
...
once = function (event, fn) { return this._once(event, fn, false); }
...
```javascript
server.offAny(function(value) {
console.log('The event was raised!');
});
```
#### emitter.once(event, listener)
Adds a **one time** listener for the event. The listener is invoked
only the first time the event is fired, after which it is removed.
```javascript
server.once('get', function (value) {
console.log('Ah, we have our first value!');
...
prependAny = function (fn) { return this._onAny(fn, true); }
...
```javascript
server.onAny(function(event, value) {
console.log('All events trigger this.');
});
```
### emitter.prependAny(listener)
Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the callback. The
listener is added to the beginning of the listeners array
```javascript
server.prependAny(function(event, value) {
console.log('All events trigger this.');
});
...
prependListener = function (type, listener) { return this._on(type, listener, true); }
...
```javascript
server.on('data', function(value) {
console.log('The event was raised!');
});
```
### emitter.prependListener(event, listener)
Adds a listener to the beginning of the listeners array for the specified event.
```javascript
server.prependListener('data', function(value1, value2, value3, ...) {
console.log('The event was raised!');
});
...
prependMany = function (event, ttl, fn) { return this._many(event, ttl, fn, true); }
...
```javascript
server.many('get', 4, function (value) {
console.log('This event will be listened to exactly four times.');
});
```
### emitter.prependMany(event, timesToListen, listener)
Adds a listener that will execute **n times** for the event before being
removed. The listener is invoked only the first **n times** the event is
fired, after which it is removed.
The listener is added to the beginning of the listeners array.
```javascript
...
prependOnceListener = function (event, fn) { return this._once(event, fn, true); }
...
```javascript
server.once('get', function (value) {
console.log('Ah, we have our first value!');
});
```
#### emitter.prependOnceListener(event, listener)
Adds a **one time** listener for the event. The listener is invoked
only the first time the event is fired, after which it is removed.
The listener is added to the beginning of the listeners array
```javascript
server.prependOnceListener('get', function (value) {
...
removeAllListeners = function (type) { if (arguments.length === 0) { !this._events || init.call(this); return this; } if (this.wildcard) { var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); var leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0); for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) { var leaf = leafs[iLeaf]; leaf._listeners = null; } } else if (this._events) { this._events[type] = null; } return this; }
...
};
server.on('get', callback);
// ...
server.removeListener('get', callback);
```
### emitter.removeAllListeners([event])
Removes all listeners, or those of the specified event.
### emitter.setMaxListeners(n)
By default EventEmitters will print a warning if more than 10 listeners
...
removeListener = function (type, listener) { if (typeof listener !== 'function') { throw new Error('removeListener only takes instances of Function'); } var handlers,leafs=[]; if(this.wildcard) { var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0); } else { // does not use listeners(), so no side effect of creating _events[type] if (!this._events[type]) return this; handlers = this._events[type]; leafs.push({_listeners:handlers}); } for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) { var leaf = leafs[iLeaf]; handlers = leaf._listeners; if (isArray(handlers)) { var position = -1; for (var i = 0, length = handlers.length; i < length; i++) { if (handlers[i] === listener || (handlers[i].listener && handlers[i].listener === listener) || (handlers[i]._origin && handlers[i]._origin === listener)) { position = i; break; } } if (position < 0) { continue; } if(this.wildcard) { leaf._listeners.splice(position, 1); } else { this._events[type].splice(position, 1); } if (handlers.length === 0) { if(this.wildcard) { delete leaf._listeners; } else { delete this._events[type]; } } this.emit("removeListener", type, listener); return this; } else if (handlers === listener || (handlers.listener && handlers.listener === listener) || (handlers._origin && handlers._origin === listener)) { if(this.wildcard) { delete leaf._listeners; } else { delete this._events[type]; } this.emit("removeListener", type, listener); } } function recursivelyGarbageCollect(root) { if (root === undefined) { return; } var keys = Object.keys(root); for (var i in keys) { var key = keys[i]; var obj = root[key]; if ((obj instanceof Function) || (typeof obj !== "object") || (obj === null)) continue; if (Object.keys(obj).length > 0) { recursivelyGarbageCollect(root[key]); } if (Object.keys(obj).length === 0) { delete root[key]; } } } recursivelyGarbageCollect(this.listenerTree); return this; }
...
server.many('get', 4, function (value) {
console.log('This event will be listened to exactly four times.');
});
```
### emitter.removeListener(event, listener)
### emitter.off(event, listener)
Remove a listener from the listener array for the specified event.
**Caution**: Calling this method changes the array indices in the listener array behind the listener.
```javascript
var callback = function(value) {
...
setMaxListeners = function (n) { if (n !== undefined) { this._maxListeners = n; if (!this._conf) this._conf = {}; this._conf.maxListeners = n; } }
...
### emitter.removeAllListeners([event])
Removes all listeners, or those of the specified event.
### emitter.setMaxListeners(n)
By default EventEmitters will print a warning if more than 10 listeners
are added to it. This is a useful default which helps finding memory leaks.
Obviously not all Emitters should be limited to 10. This function allows
that to be increased. Set to zero for unlimited.
...