2.2 Chat Emitter
We're going to create a custom chat EventEmitter.
Task 1:
Create a new
Task 2:
Next, let's listen for the 'message' event on our new chat object. Remember to add a callback that accepts the
Task 3:
Log the message to the console using
```js var events = require('events'); var EventEmitter = events.EventEmitter; var logger = new EventEmitter(); logger.on('message', function(message){ console.log("ERR: " + message); }); ```
2.3 Emitting Events
Read the existing code below and modify it to emit events.
Task 1:
On the chat object, emit the 'join' event and pass in a custom message as a string.
Task 2:
Now emit the 'message' event on the chat object. Just like before, remember to pass in a custom message as a string.
```js var events = require('events'); var EventEmitter = events.EventEmitter; var chat = new EventEmitter(); var users = [], chatlog = []; chat.on('message', function(message) { chatlog.push(message); }); chat.on('join', function(nickname) { users.push(nickname); }); chat.emit('join', "Hello"); chat.emit('message', "Message:"); ```
2.4 Request Event
Just like you saw in the video, refactor the HTTP server code to explicitly bind a callback to the 'request' event using the
Task 1:
Add an event listener on the
Task 2:
Move the logic for handling the request from the
```js var http = require('http'); var server = http.createServer(); server.on('request', function(request, response){ response.writeHead(200); response.write("Hello, this is dog"); response.end(); }); server.listen(8080); ```
2.5 Listening Twice
Who said you can only listen for an event once?
Task 1:
Add a second 'request' handler to the HTTP server.
Task 2:
From inside of the new handler, log the message "New request coming in..." using
```js var http = require('http'); var server = http.createServer(); server.on('request', function(request, response) { response.writeHead(200); response.write("Hello, this is dog"); response.end(); }); server.on('request', function(request, response){ console.log("New request coming in..."); }); server.listen(8080); ```
2.6 Listening for Close
Like our parents always used to say, listening is more important than talking! Modify the server so that we know when it's closed down.
Task 1:
Listen for the 'close' event on the server. The event listener should take a callback function that accepts no arguments.
Task 2:
Inside the 'close' callback, log the message "Closing down the server...".
```js var http = require('http'); var server = http.createServer(); server.on('request', function(request, response) { response.writeHead(200); response.write("Hello, this is dog"); response.end(); }); server.on('request', function(request, response) { console.log("New request coming in..."); }); server.on('close', function(){ console.log("Closing down the server..."); }); server.listen(8080); ```
沒有留言:
張貼留言