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
<p><ahref="https://github.com/jjmax75/openjs-nodejs-application-developer-study-guide/tree/master/{{ page.inputPath }}">Edit this page on GitHub</a></p>
Copy file name to clipboardExpand all lines: events/index.md
+9-10Lines changed: 9 additions & 10 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,10 +1,9 @@
1
1
---
2
2
layout: default.njk
3
3
title: Events
4
+
url: events
4
5
---
5
6
6
-
# Events
7
-
8
7
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
8
10
9
Objects that emit events extend the `EventEmitter` class. These objects expose an `on` method that allows one or more functions to be attached to named events emitted by the object.
@@ -15,23 +14,23 @@ When the EventEmitter object emits an event, all of the functions attached to th
15
14
16
15
This example creates an event listener for `foo` events, and an event emitter to fire these events.
17
16
18
-
```
19
-
const { EventEmitter } = require('events');
17
+
```javascript
18
+
const { EventEmitter } =require("events");
20
19
21
20
// create a listener function. These can be arrow functions, but will
22
21
// loose `this` refering to the EventEmitter object
23
22
constfoo=functionfoo() {
24
-
console.log('foo executed.', this)
25
-
}
23
+
console.log("foo executed.", this);
24
+
};
26
25
27
26
// create an emitter and bind some events to it
28
-
const eventEmitter = new EventEmitter()
27
+
consteventEmitter=newEventEmitter();
29
28
30
29
// Bind the connection event with the listner1 function
31
-
eventEmitter.on('foo', foo)
30
+
eventEmitter.on("foo", foo);
32
31
33
32
// fire the event
34
-
eventEmitter.emit('foo')
33
+
eventEmitter.emit("foo");
35
34
```
36
35
37
36
## Passing parameters
@@ -64,4 +63,4 @@ Imagine we are building a SaaS that does a number of things when a user creates
64
63
is created, we want to emit a `userCreated` event. One of the listeners for this will email a confirmation
65
64
email to that user.
66
65
67
-
Build an event emitter to simulate the `userCreated` event, and an event listener that sends a confirmation email. There is a mock emailer class in the folder that has a method `send`, which expects an email address and a message body as the parameters.
66
+
Build an event emitter to simulate the `userCreated` event, and an event listener that sends a confirmation email. There is a mock emailer class in the folder that has a method `send`, which expects an email address and a message body as the parameters.
0 commit comments