Skip to content

Commit 31df2af

Browse files
Ian-ReadIan-Read
authored andcommitted
Events exercise + solution
1 parent 9773162 commit 31df2af

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

events/exercise/emailer.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
module.exports = class Emailer {
2+
3+
send (to, body) {
4+
console.log(`Sending email to ${to} with body '${body}'`)
5+
}
6+
7+
}

events/exercise/solution.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
2+
const Emailer = require('./emailer')
3+
const { EventEmitter } = require('events')
4+
5+
const emailer = new Emailer()
6+
7+
const userEvents = new EventEmitter()
8+
9+
const sendWelcomeEmail = function sendWelcomeEmail(emailAddress) {
10+
emailer.send(emailAddress, `Welcome to our app!`)
11+
}
12+
13+
userEvents.on('newUser', sendWelcomeEmail)
14+
15+
userEvents.emit('newUser', 'example@example.com')

events/index.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,3 +62,10 @@ require('events)
6262

6363
Main concept = listeners listen for events, that are emitted from emitters.
6464

65+
## Exercise
66+
67+
Image we are building a SaaS that does a number of things when a user creates an account. functionality that sends emails "confirmation" to a user when they create an account.
68+
69+
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.
70+
71+
Use this to send a welcome email when a `userCreated` event is fired.

0 commit comments

Comments
 (0)