You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: events/index.md
+34-4Lines changed: 34 additions & 4 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -3,13 +3,15 @@ layout: default.njk
3
3
title: Events
4
4
---
5
5
6
-
Events
7
-
8
6
The Node.js core API is built around the idea of events being "emitted" and "listened" to. Objects called "emitters" emit _named_ events, that are picked up by "listener" functions.
9
7
10
8
Objects that emit events extend the `EventEmitter` class. These objects expose an eventEmitter.on() function that allows one or more functions to be attached to named events emitted by the object.
11
9
12
-
When the EventEmitter object emits an event, all of the functions attached to that specific event are called synchronously, in the order they were added. This is to prevent race conditions and logic errors. They can switch to an async mode using `setImmediate`.
10
+
When the EventEmitter object emits an event, all of the functions attached to that specific event are called _synchronously_, in the order they were added. This is to prevent race conditions and logic errors. They can switch to an async mode using `setImmediate`.
11
+
12
+
## A Simple Example
13
+
14
+
This example creates an event listener for `foo` events, and an event emitter to fire these events.
13
15
14
16
```
15
17
const { EventEmitter } = require('events');
@@ -30,5 +32,33 @@ eventEmitter.on('foo', foo)
30
32
eventEmitter.emit('foo')
31
33
```
32
34
33
-
Why?
35
+
## Passing parameters
36
+
37
+
When an event is emitted using the `emit` method, the subsequent arguments are passed through to the listeners. For example:
38
+
39
+
```
40
+
const foo = function foo(bar) {
41
+
console.log(`foo has been passed ${bar}`)
42
+
}
43
+
44
+
// Bind the connection event with the listner1 function
45
+
eventEmitter.on('foo', foo)
46
+
47
+
// fire the event
48
+
eventEmitter.emit('foo', 'bar')
49
+
```
50
+
51
+
## Objects:
52
+
53
+
```
54
+
require('events)
55
+
```
56
+
57
+
## Methods
58
+
59
+
`on(eventName, listenerFunction)`
60
+
61
+
## Summary
62
+
63
+
Main concept = listeners listen for events, that are emitted from emitters.
0 commit comments