Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Build a Simple Dynamic Site with Node.js Creating a Simple Server in Node.js Preparing & Planning

Oriol Jurnet
Oriol Jurnet
9,515 Points

EventEmitter | using "this" in Node | util.inherits() | new Profile -- Many explanations Missing

Hi,

I've just landed in this course following the "Full Stack JS" Track and I have the feeling something is missing. Previous courses about NodeJS in this track were pretty clear to me but now I face this one with "already written" code in the first step and without any explanation on the points I mention in this question's title. Am I missing some course or videos here?

Thanks in advance!

2 Answers

Hi,

I was having similar concerns when I originally did that course. However, I ended up researching the EventEmitter class of the node core modules and found some cool stuff on it. In this video particularly we are creating our own class 'Profile' which inherits all methods and properties from the node module EventEmitter. We can use event emitter to emit our own custom events in our application. We can then listen to these events and handle them however we want to. I included a basic example (without any error handling stuff) below on how we can create our own EventEmitter and use it in other files.

Imagine this is in file: MyOwnEmitter.js

//Here at the top of the file you are requiring some core modules from node.js
//what it does: it 'imports' some core functionalities from node.js
//EventEmitter: The base 'class' for your  'custom' event emitter
var EventEmitter = require("events").EventEmitter;
//https: Allows you to make https calls to other resources (here our own made up api)
var https = require("https");
//util: is used so you can extend EventEmitter and create your own 'child' class of it.
var util = require("util");

//Now create our own 'class constructor'. We do this so later in our application we can instantiate our eventemitter.
function MyOwnEmitter() {
      //Call the Node.js EventEmitter constructor (you need to do this so you can inherit from it later)
      EventEmitter.call(this);

      //We create a local variable 'self' which just refers to itself so we do not create any scoping issues when doing our api call
      var self = this;

      //let's do our api call to some made up api that returns weather data, by using the https module from above.
     //first parameter: the url we are requesting. second parameter: a callback function to run after the request is made
      var request = https.get('https://someMadeUpWeatherApi/', function(response) {
                     //set the body just to an initial string initially
                     var body = "";
                     //Here we listen for the 'data' event and add to the body as the data is coming to our server
                     response.on('data',function(chunk){
                           body += chunk;
                           //HERE IS KEY: WE ARE ACTUALLY EMITTING OUR OWN EVENT NOW
                           self.emit('dataFromMyApiIsHere', chunck);
                     });

                    //Here we listen for the 'end' event which is fired once our response is done. Which means we can parse the data
                   response.on('end',function() {
                         //parse the body into json so we can easily read it wherever we want to later
                         var json = JSON.parse(body);
                         //HERE IS KEY: WE ARE ACTUALLY EMITTING OUR OWN EVENT NOW AGAIN
                         self.emit('endOfOurApiData', json);
                   });
      }

}

//Here we inherit from EventEmitter so our 'class' MyOwnEmitter can use all of the same methods as EventEmitter. like //'emit' and 'on' as we have already seen above in self.emit etc.
util.inhertis(MyOwnEmitter, EventEmitter);

//export our class/module so we can use it in other files
module.exports = MyOwnEmitter;

Imagine now this is in the file app.js

var myOwnEmitter = require('./MyOwnEmitter.js');

//now we instantiate our own emitter;
//What happens at this moment -- it runs through everything we put in the function MyOwnEmitter above. 
//Including the api call to our made up weather api
var myOwnEmitterInstance = new myOwnEmitter();


//Now we can listen for the events 'dataFromApiIsHere' and 'endOfOurApiData' we emitted above
myOwnEmitterInstance.on('dataFromApiIsHere',function(chunk){
         console.log(chunck);
});

myOwnEmitterInstance.on('endOfOurApiData',function(json){
         //this will actually be all of the data our weather api returned in json format!!!
         console.log(json);
});

Why we need to call EventEmiter in 'this' context, I am't clear.

Here This is the the global object, And i am not sure but i think EventEmiter is also in global object.