c14994e5bf4a591c1ecdedb825bb14bd9d94b16c
[platform/upstream/nodejs.git] / doc / api / events.markdown
1 # Events
2
3     Stability: 2 - Stable
4
5 <!--type=module-->
6
7 Many objects in Node.js emit events: a
8 [`net.Server`](net.html#net_class_net_server) emits an event each time a peer
9 connects to it, a [`fs.ReadStream`](fs.html#fs_class_fs_readstream) emits an
10 event when the file is
11 opened. All objects which emit events are instances of `events.EventEmitter`.
12 You can access this module by doing: `require("events");`
13
14 Typically, event names are represented by a camel-cased string, however,
15 there aren't any strict restrictions on that, as any string will be accepted.
16
17 Functions can then be attached to objects, to be executed when an event
18 is emitted. These functions are called _listeners_. Inside a listener
19 function, `this` refers to the `EventEmitter` that the listener was
20 attached to.
21
22
23 ## Class: events.EventEmitter
24
25 Use `require('events')` to access the EventEmitter class.
26
27 ```javascript
28 var EventEmitter = require('events');
29 ```
30
31 When an `EventEmitter` instance experiences an error, the typical action is
32 to emit an `'error'` event.  Error events are treated as a special case in
33 Node.js.  If there is no listener for it, then the default action is to print
34 a stack trace and exit the program.
35
36 All EventEmitters emit the event `'newListener'` when new listeners are
37 added and `'removeListener'` when a listener is removed.
38
39 ### Inheriting from 'EventEmitter'
40
41 Inheriting from `EventEmitter` is no different from inheriting from any other
42 constructor function. For example:
43
44     'use strict';
45     const util = require('util');
46     const EventEmitter = require('events');
47
48     function MyEventEmitter() {
49       // Initialize necessary properties from `EventEmitter` in this instance
50       EventEmitter.call(this);
51     }
52
53     // Inherit functions from `EventEmitter`'s prototype
54     util.inherits(MyEventEmitter, EventEmitter);
55
56 ### Class Method: EventEmitter.listenerCount(emitter, event)
57
58     Stability: 0 - Deprecated: Use [emitter.listenerCount][] instead.
59
60 Returns the number of listeners for a given event.
61
62 ### Event: 'newListener'
63
64 * `event` {String} The event name
65 * `listener` {Function} The event handler function
66
67 This event is emitted *before* a listener is added. When this event is
68 triggered, the listener has not been added to the array of listeners for the
69 `event`. Any listeners added to the event `name` in the newListener event
70 callback will be added *before* the listener that is in the process of being
71 added.
72
73 ### Event: 'removeListener'
74
75 * `event` {String} The event name
76 * `listener` {Function} The event handler function
77
78 This event is emitted *after* a listener is removed.  When this event is
79 triggered, the listener has been removed from the array of listeners for the
80 `event`.
81
82 ### EventEmitter.defaultMaxListeners
83
84 [`emitter.setMaxListeners(n)`](#events_emitter_setmaxlisteners_n) sets the
85 maximum on a per-instance basis.
86 This class property lets you set it for *all* `EventEmitter` instances,
87 current and future, effective immediately. Use with care.
88
89 Note that [`emitter.setMaxListeners(n)`](#events_emitter_setmaxlisteners_n)
90 still has precedence over `EventEmitter.defaultMaxListeners`.
91
92 ### emitter.addListener(event, listener)
93
94 Alias for `emitter.on(event, listener)`.
95
96 ### emitter.emit(event[, arg1][, arg2][, ...])
97
98 Calls each of the listeners in order with the supplied arguments.
99
100 Returns `true` if event had listeners, `false` otherwise.
101
102 ### emitter.getMaxListeners()
103
104 Returns the current max listener value for the emitter which is either set by
105 [`emitter.setMaxListeners(n)`](#events_emitter_setmaxlisteners_n) or defaults to
106 [`EventEmitter.defaultMaxListeners`](#events_eventemitter_defaultmaxlisteners).
107
108 This can be useful to increment/decrement max listeners to avoid the warning
109 while not being irresponsible and setting a too big number.
110
111     emitter.setMaxListeners(emitter.getMaxListeners() + 1);
112     emitter.once('event', function () {
113       // do stuff
114       emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
115     });
116
117 ### emitter.listenerCount(type)
118
119 * `type` {Value} The type of event
120
121 Returns the number of listeners listening to the `type` of event.
122
123 ### emitter.listeners(event)
124
125 Returns a copy of the array of listeners for the specified event.
126
127     server.on('connection', function (stream) {
128       console.log('someone connected!');
129     });
130     console.log(util.inspect(server.listeners('connection'))); // [ [Function] ]
131
132 ### emitter.on(event, listener)
133
134 Adds a listener to the end of the listeners array for the specified `event`.
135 No checks are made to see if the `listener` has already been added. Multiple
136 calls passing the same combination of `event` and `listener` will result in the
137 `listener` being added multiple times.
138
139     server.on('connection', function (stream) {
140       console.log('someone connected!');
141     });
142
143 Returns emitter, so calls can be chained.
144
145 ### emitter.once(event, listener)
146
147 Adds a **one time** listener for the event. This listener is
148 invoked only the next time the event is fired, after which
149 it is removed.
150
151     server.once('connection', function (stream) {
152       console.log('Ah, we have our first user!');
153     });
154
155 Returns emitter, so calls can be chained.
156
157 ### emitter.removeAllListeners([event])
158
159 Removes all listeners, or those of the specified event. It's not a good idea to
160 remove listeners that were added elsewhere in the code, especially when it's on
161 an emitter that you didn't create (e.g. sockets or file streams).
162
163 Returns emitter, so calls can be chained.
164
165 ### emitter.removeListener(event, listener)
166
167 Removes a listener from the listener array for the specified event.
168 **Caution**: changes array indices in the listener array behind the listener.
169
170     var callback = function(stream) {
171       console.log('someone connected!');
172     };
173     server.on('connection', callback);
174     // ...
175     server.removeListener('connection', callback);
176
177 `removeListener` will remove, at most, one instance of a listener from the
178 listener array. If any single listener has been added multiple times to the
179 listener array for the specified `event`, then `removeListener` must be called
180 multiple times to remove each instance.
181
182 Returns emitter, so calls can be chained.
183
184 ### emitter.setMaxListeners(n)
185
186 By default EventEmitters will print a warning if more than 10 listeners are
187 added for a particular event. This is a useful default which helps finding
188 memory leaks. Obviously not all Emitters should be limited to 10. This function
189 allows that to be increased. Set to `Infinity` (or `0`) for unlimited.
190
191 Returns emitter, so calls can be chained.
192
193 [emitter.listenerCount]: #events_emitter_listenercount_type