3 * https://github.com/hij1nx/EventEmitter2
5 * Copyright (c) 2013 hij1nx
6 * Licensed under the MIT license.
8 ;!function(undefined) {
10 var isArray = Array.isArray ? Array.isArray : function _isArray(obj) {
11 return Object.prototype.toString.call(obj) === "[object Array]";
13 var defaultMaxListeners = 10;
18 configure.call(this, this._conf);
22 function configure(conf) {
27 conf.delimiter && (this.delimiter = conf.delimiter);
28 conf.maxListeners && (this._events.maxListeners = conf.maxListeners);
29 conf.wildcard && (this.wildcard = conf.wildcard);
30 conf.newListener && (this.newListener = conf.newListener);
33 this.listenerTree = {};
38 function EventEmitter(conf) {
40 this.newListener = false;
41 configure.call(this, conf);
45 // Attention, function return type now is array, always !
46 // It has zero elements if no any matches found and one or more
47 // elements (leafs) if there are matches
49 function searchListenerTree(handlers, type, tree, i) {
53 var listeners=[], leaf, len, branch, xTree, xxTree, isolatedBranch, endReached,
54 typeLength = type.length, currentType = type[i], nextType = type[i+1];
55 if (i === typeLength && tree._listeners) {
57 // If at the end of the event(s) list and the tree has listeners
58 // invoke those listeners.
60 if (typeof tree._listeners === 'function') {
61 handlers && handlers.push(tree._listeners);
64 for (leaf = 0, len = tree._listeners.length; leaf < len; leaf++) {
65 handlers && handlers.push(tree._listeners[leaf]);
71 if ((currentType === '*' || currentType === '**') || tree[currentType]) {
73 // If the event emitted is '*' at this part
74 // or there is a concrete match at this patch
76 if (currentType === '*') {
77 for (branch in tree) {
78 if (branch !== '_listeners' && tree.hasOwnProperty(branch)) {
79 listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+1));
83 } else if(currentType === '**') {
84 endReached = (i+1 === typeLength || (i+2 === typeLength && nextType === '*'));
85 if(endReached && tree._listeners) {
86 // The next element has a _listeners, add it to the handlers.
87 listeners = listeners.concat(searchListenerTree(handlers, type, tree, typeLength));
90 for (branch in tree) {
91 if (branch !== '_listeners' && tree.hasOwnProperty(branch)) {
92 if(branch === '*' || branch === '**') {
93 if(tree[branch]._listeners && !endReached) {
94 listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], typeLength));
96 listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i));
97 } else if(branch === nextType) {
98 listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+2));
100 // No match on this one, shift into the tree but not in the type array.
101 listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i));
108 listeners = listeners.concat(searchListenerTree(handlers, type, tree[currentType], i+1));
114 // If the listener tree will allow any match for this part,
115 // then recursively explore all branches of the tree
117 searchListenerTree(handlers, type, xTree, i+1);
123 if(xxTree._listeners) {
124 // If we have a listener on a '**', it will catch all, so add its handler.
125 searchListenerTree(handlers, type, xxTree, typeLength);
128 // Build arrays of matching next branches and others.
129 for(branch in xxTree) {
130 if(branch !== '_listeners' && xxTree.hasOwnProperty(branch)) {
131 if(branch === nextType) {
132 // We know the next element will match, so jump twice.
133 searchListenerTree(handlers, type, xxTree[branch], i+2);
134 } else if(branch === currentType) {
135 // Current node matches, move into the tree.
136 searchListenerTree(handlers, type, xxTree[branch], i+1);
139 isolatedBranch[branch] = xxTree[branch];
140 searchListenerTree(handlers, type, { '**': isolatedBranch }, i+1);
144 } else if(xxTree._listeners) {
145 // We have reached the end and still on a '**'
146 searchListenerTree(handlers, type, xxTree, typeLength);
147 } else if(xxTree['*'] && xxTree['*']._listeners) {
148 searchListenerTree(handlers, type, xxTree['*'], typeLength);
155 function growListenerTree(type, listener) {
157 type = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
160 // Looks for two consecutive '**', if so, don't add the event at all.
162 for(var i = 0, len = type.length; i+1 < len; i++) {
163 if(type[i] === '**' && type[i+1] === '**') {
168 var tree = this.listenerTree;
169 var name = type.shift();
179 if (type.length === 0) {
181 if (!tree._listeners) {
182 tree._listeners = listener;
184 else if(typeof tree._listeners === 'function') {
185 tree._listeners = [tree._listeners, listener];
187 else if (isArray(tree._listeners)) {
189 tree._listeners.push(listener);
191 if (!tree._listeners.warned) {
193 var m = defaultMaxListeners;
195 if (typeof this._events.maxListeners !== 'undefined') {
196 m = this._events.maxListeners;
199 if (m > 0 && tree._listeners.length > m) {
201 tree._listeners.warned = true;
202 console.error('(node) warning: possible EventEmitter memory ' +
203 'leak detected. %d listeners added. ' +
204 'Use emitter.setMaxListeners() to increase limit.',
205 tree._listeners.length);
217 // By default EventEmitters will print a warning if more than
218 // 10 listeners are added to it. This is a useful default which
219 // helps finding memory leaks.
221 // Obviously not all Emitters should be limited to 10. This function allows
222 // that to be increased. Set to zero for unlimited.
224 EventEmitter.prototype.delimiter = '.';
226 EventEmitter.prototype.setMaxListeners = function(n) {
227 this._events || init.call(this);
228 this._events.maxListeners = n;
229 if (!this._conf) this._conf = {};
230 this._conf.maxListeners = n;
233 EventEmitter.prototype.event = '';
235 EventEmitter.prototype.once = function(event, fn) {
236 this.many(event, 1, fn);
240 EventEmitter.prototype.many = function(event, ttl, fn) {
243 if (typeof fn !== 'function') {
244 throw new Error('many only accepts instances of Function');
247 function listener() {
249 self.off(event, listener);
251 fn.apply(this, arguments);
254 listener._origin = fn;
256 this.on(event, listener);
261 EventEmitter.prototype.emit = function() {
263 this._events || init.call(this);
265 var type = arguments[0];
267 if (type === 'newListener' && !this.newListener) {
268 if (!this._events.newListener) { return false; }
271 // Loop through the *_all* functions and invoke them.
273 var l = arguments.length;
274 var args = new Array(l - 1);
275 for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
276 for (i = 0, l = this._all.length; i < l; i++) {
278 this._all[i].apply(this, args);
282 // If there is no 'error' event listener then throw.
283 if (type === 'error') {
286 !this._events.error &&
287 !(this.wildcard && this.listenerTree.error)) {
289 if (arguments[1] instanceof Error) {
290 throw arguments[1]; // Unhandled 'error' event
292 throw new Error("Uncaught, unspecified 'error' event.");
302 var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
303 searchListenerTree.call(this, handler, ns, this.listenerTree, 0);
306 handler = this._events[type];
309 if (typeof handler === 'function') {
311 if (arguments.length === 1) {
314 else if (arguments.length > 1)
315 switch (arguments.length) {
317 handler.call(this, arguments[1]);
320 handler.call(this, arguments[1], arguments[2]);
324 var l = arguments.length;
325 var args = new Array(l - 1);
326 for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
327 handler.apply(this, args);
332 var l = arguments.length;
333 var args = new Array(l - 1);
334 for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
336 var listeners = handler.slice();
337 for (var i = 0, l = listeners.length; i < l; i++) {
339 listeners[i].apply(this, args);
341 return (listeners.length > 0) || !!this._all;
349 EventEmitter.prototype.on = function(type, listener) {
351 if (typeof type === 'function') {
356 if (typeof listener !== 'function') {
357 throw new Error('on only accepts instances of Function');
359 this._events || init.call(this);
361 // To avoid recursion in the case that type == "newListeners"! Before
362 // adding it to the listeners, first emit "newListeners".
363 this.emit('newListener', type, listener);
366 growListenerTree.call(this, type, listener);
370 if (!this._events[type]) {
371 // Optimize the case of one listener. Don't need the extra array object.
372 this._events[type] = listener;
374 else if(typeof this._events[type] === 'function') {
375 // Adding the second element, need to change to array.
376 this._events[type] = [this._events[type], listener];
378 else if (isArray(this._events[type])) {
379 // If we've already got an array, just append.
380 this._events[type].push(listener);
382 // Check for listener leak
383 if (!this._events[type].warned) {
385 var m = defaultMaxListeners;
387 if (typeof this._events.maxListeners !== 'undefined') {
388 m = this._events.maxListeners;
391 if (m > 0 && this._events[type].length > m) {
393 this._events[type].warned = true;
394 console.error('(node) warning: possible EventEmitter memory ' +
395 'leak detected. %d listeners added. ' +
396 'Use emitter.setMaxListeners() to increase limit.',
397 this._events[type].length);
405 EventEmitter.prototype.onAny = function(fn) {
407 if (typeof fn !== 'function') {
408 throw new Error('onAny only accepts instances of Function');
415 // Add the function to the event listener collection.
420 EventEmitter.prototype.addListener = EventEmitter.prototype.on;
422 EventEmitter.prototype.off = function(type, listener) {
423 if (typeof listener !== 'function') {
424 throw new Error('removeListener only takes instances of Function');
427 var handlers,leafs=[];
430 var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
431 leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0);
434 // does not use listeners(), so no side effect of creating _events[type]
435 if (!this._events[type]) return this;
436 handlers = this._events[type];
437 leafs.push({_listeners:handlers});
440 for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) {
441 var leaf = leafs[iLeaf];
442 handlers = leaf._listeners;
443 if (isArray(handlers)) {
447 for (var i = 0, length = handlers.length; i < length; i++) {
448 if (handlers[i] === listener ||
449 (handlers[i].listener && handlers[i].listener === listener) ||
450 (handlers[i]._origin && handlers[i]._origin === listener)) {
461 leaf._listeners.splice(position, 1);
464 this._events[type].splice(position, 1);
467 if (handlers.length === 0) {
469 delete leaf._listeners;
472 delete this._events[type];
477 else if (handlers === listener ||
478 (handlers.listener && handlers.listener === listener) ||
479 (handlers._origin && handlers._origin === listener)) {
481 delete leaf._listeners;
484 delete this._events[type];
492 EventEmitter.prototype.offAny = function(fn) {
493 var i = 0, l = 0, fns;
494 if (fn && this._all && this._all.length > 0) {
496 for(i = 0, l = fns.length; i < l; i++) {
508 EventEmitter.prototype.removeListener = EventEmitter.prototype.off;
510 EventEmitter.prototype.removeAllListeners = function(type) {
511 if (arguments.length === 0) {
512 !this._events || init.call(this);
517 var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
518 var leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0);
520 for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) {
521 var leaf = leafs[iLeaf];
522 leaf._listeners = null;
526 if (!this._events[type]) return this;
527 this._events[type] = null;
532 EventEmitter.prototype.listeners = function(type) {
535 var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
536 searchListenerTree.call(this, handlers, ns, this.listenerTree, 0);
540 this._events || init.call(this);
542 if (!this._events[type]) this._events[type] = [];
543 if (!isArray(this._events[type])) {
544 this._events[type] = [this._events[type]];
546 return this._events[type];
549 EventEmitter.prototype.listenersAny = function() {
560 if (typeof define === 'function' && define.amd) {
561 // AMD. Register as an anonymous module.
565 } else if (typeof exports === 'object') {
567 exports.EventEmitter2 = EventEmitter;
571 window.EventEmitter2 = EventEmitter;