Events

Screenshot 2022-08-20 at 2.37.00 AM.png

Here, we should be able to handle events. For example, user clicks a button, we handle the event. User hover over something, we handle the event.

This, style of programming is called the event driven programming. Now, this could be also handled on the server side in node js.

The idea is: We listen for specific events and register functions that will execute in response to those events. So, once our event takes place, callback function fires.

Very basice events example:

Screenshot 2022-08-20 at 2.45.12 AM.png

Screenshot 2022-08-20 at 2.43.10 AM.png

Here, in the on method we are passing a string, which is going to be the name of the event, as well as the callback function. And when this event takes place we will do someting. Like in this case print data received. Note: on subscribes to an event.

We, can even do some other logic while listening to the same event.

Screenshot 2022-08-20 at 2.48.14 AM.png

Now, note here the order matters. So, now if I place my event emit above the listeners.

Screenshot 2022-08-20 at 2.49.43 AM.png

You can see that the console is empty. Why? Because we have first already emitted the event and then I am listening for it. So, first we would want to listen for the event and then only emit it.

Now, we can also pass arguments when listening to the events.

Screenshot 2022-08-20 at 2.53.16 AM.png

Now, note that in the second on we did not have any args. But this did not broke the program.