b42f086ee777a7d52d15505d1b0d2e5a357cb0ec
[platform/upstream/nodejs.git] / lib / events.js
1 // Copyright Joyent, Inc. and other Node contributors.
2 //
3 // Permission is hereby granted, free of charge, to any person obtaining a
4 // copy of this software and associated documentation files (the
5 // "Software"), to deal in the Software without restriction, including
6 // without limitation the rights to use, copy, modify, merge, publish,
7 // distribute, sublicense, and/or sell copies of the Software, and to permit
8 // persons to whom the Software is furnished to do so, subject to the
9 // following conditions:
10 //
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
13 //
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22 var isArray = Array.isArray;
23
24 function EventEmitter() { }
25 exports.EventEmitter = EventEmitter;
26
27 // By default EventEmitters will print a warning if more than
28 // 10 listeners are added to it. This is a useful default which
29 // helps finding memory leaks.
30 //
31 // Obviously not all Emitters should be limited to 10. This function allows
32 // that to be increased. Set to zero for unlimited.
33 var defaultMaxListeners = 10;
34 EventEmitter.prototype.setMaxListeners = function(n) {
35   if (!this._events) this._events = {};
36   this._maxListeners = n;
37 };
38
39
40 EventEmitter.prototype.emit = function() {
41   var type = arguments[0];
42   // If there is no 'error' event listener then throw.
43   if (type === 'error') {
44     if (!this._events || !this._events.error ||
45         (isArray(this._events.error) && !this._events.error.length))
46     {
47       if (arguments[1] instanceof Error) {
48         throw arguments[1]; // Unhandled 'error' event
49       } else {
50         throw new Error("Uncaught, unspecified 'error' event.");
51       }
52       return false;
53     }
54   }
55
56   if (!this._events) return false;
57   var handler = this._events[type];
58   if (!handler) return false;
59
60   if (typeof handler == 'function') {
61     switch (arguments.length) {
62       // fast cases
63       case 1:
64         handler.call(this);
65         break;
66       case 2:
67         handler.call(this, arguments[1]);
68         break;
69       case 3:
70         handler.call(this, arguments[1], arguments[2]);
71         break;
72       // slower
73       default:
74         var l = arguments.length;
75         var args = new Array(l - 1);
76         for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
77         handler.apply(this, args);
78     }
79     return true;
80
81   } else if (isArray(handler)) {
82     var l = arguments.length;
83     var args = new Array(l - 1);
84     for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
85
86     var listeners = handler.slice();
87     for (var i = 0, l = listeners.length; i < l; i++) {
88       listeners[i].apply(this, args);
89     }
90     return true;
91
92   } else {
93     return false;
94   }
95 };
96
97 // EventEmitter is defined in src/node_events.cc
98 // EventEmitter.prototype.emit() is also defined there.
99 EventEmitter.prototype.addListener = function(type, listener) {
100   if ('function' !== typeof listener) {
101     throw new Error('addListener only takes instances of Function');
102   }
103
104   if (!this._events) this._events = {};
105
106   // To avoid recursion in the case that type == "newListeners"! Before
107   // adding it to the listeners, first emit "newListeners".
108   this.emit('newListener', type, typeof listener.listener === 'function' ?
109             listener.listener : listener);
110
111   if (!this._events[type]) {
112     // Optimize the case of one listener. Don't need the extra array object.
113     this._events[type] = listener;
114   } else if (isArray(this._events[type])) {
115
116     // If we've already got an array, just append.
117     this._events[type].push(listener);
118
119   } else {
120     // Adding the second element, need to change to array.
121     this._events[type] = [this._events[type], listener];
122
123   }
124
125   // Check for listener leak
126   if (isArray(this._events[type]) && !this._events[type].warned) {
127     var m;
128     if (this._maxListeners !== undefined) {
129       m = this._maxListeners;
130     } else {
131       m = defaultMaxListeners;
132     }
133
134     if (m && m > 0 && this._events[type].length > m) {
135       this._events[type].warned = true;
136       console.error('(node) warning: possible EventEmitter memory ' +
137                     'leak detected. %d listeners added. ' +
138                     'Use emitter.setMaxListeners() to increase limit.',
139                     this._events[type].length);
140       console.trace();
141     }
142   }
143
144   return this;
145 };
146
147 EventEmitter.prototype.on = EventEmitter.prototype.addListener;
148
149 EventEmitter.prototype.once = function(type, listener) {
150   if ('function' !== typeof listener) {
151     throw new Error('.once only takes instances of Function');
152   }
153
154   var self = this;
155   function g() {
156     self.removeListener(type, g);
157     listener.apply(this, arguments);
158   };
159
160   g.listener = listener;
161   self.on(type, g);
162
163   return this;
164 };
165
166 EventEmitter.prototype.removeListener = function(type, listener) {
167   if ('function' !== typeof listener) {
168     throw new Error('removeListener only takes instances of Function');
169   }
170
171   // does not use listeners(), so no side effect of creating _events[type]
172   if (!this._events || !this._events[type]) return this;
173
174   var list = this._events[type];
175
176   if (isArray(list)) {
177     var position = -1;
178     for (var i = 0, length = list.length; i < length; i++) {
179       if (list[i] === listener ||
180           (list[i].listener && list[i].listener === listener))
181       {
182         position = i;
183         break;
184       }
185     }
186
187     if (position < 0) return this;
188     list.splice(position, 1);
189   } else if (list === listener ||
190              (list.listener && list.listener === listener))
191   {
192     delete this._events[type];
193   }
194
195   return this;
196 };
197
198 EventEmitter.prototype.removeAllListeners = function(type) {
199   if (arguments.length === 0) {
200     this._events = {};
201     return this;
202   }
203
204   var events = this._events && this._events[type];
205   if (!events) return this;
206
207   if (isArray(events)) {
208     events.splice(0);
209   } else {
210     this._events[type] = null;
211   }
212
213   return this;
214 };
215
216 EventEmitter.prototype.listeners = function(type) {
217   if (!this._events) this._events = {};
218   if (!this._events[type]) this._events[type] = [];
219   if (!isArray(this._events[type])) {
220     this._events[type] = [this._events[type]];
221   }
222   return this._events[type];
223 };