Skip to content

Commit 9773162

Browse files
Ian-ReadIan-Read
authored andcommitted
Added more overview
1 parent 991cc09 commit 9773162

File tree

2 files changed

+46
-4
lines changed

2 files changed

+46
-4
lines changed

events/example-with-param.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
const { EventEmitter } = require('events')
2+
3+
const foo = function foo(bar) {
4+
console.log(`foo has been passed ${bar}`)
5+
}
6+
7+
// create an emitter and bind some events to it
8+
const eventEmitter = new EventEmitter()
9+
10+
eventEmitter.on('foo', foo)
11+
12+
eventEmitter.emit('foo', 'bar')

events/index.md

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,15 @@ layout: default.njk
33
title: Events
44
---
55

6-
Events
7-
86
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.
97

108
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.
119

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.
1315

1416
```
1517
const { EventEmitter } = require('events');
@@ -30,5 +32,33 @@ eventEmitter.on('foo', foo)
3032
eventEmitter.emit('foo')
3133
```
3234

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.
3464

0 commit comments

Comments
 (0)