11

I am new to Node, and I am struggling to understand the main difference between Events and Functions. Both need to be triggered, so why do we need an Event at all if we have to trigger it anyway?

How is it different than having a Function triggered?

Example code:

var events = require('events');
var eventEmitter = new events.EventEmitter();

eventEmitter.on('event1', function () {
    console.log('Event 1 executed.');
    eventEmitter.emit('event2');
});

eventEmitter.on('event2', function() {
    console.log('Event 2 executed.');
});

eventEmitter.emit('event1');
console.log('Program Ended.');

We can achieve the same result by functions, right?

I am sure this has some serious importance in Node (otherwise it would not exist, lol), but I am struggling to understand it.

Help appreciated! :)

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Ariel Weinberger
  • 2,195
  • 4
  • 23
  • 49
  • 1
    A function is *called*, like a method, by passing arguments to it: `…(…)`. It's not "triggered". – Bergi Feb 14 '16 at 18:40
  • 2
    How would you achieve "the same result" by functions? And notice that you already *are using functions* as event handlers in your `EventEmitter` solution. – Bergi Feb 14 '16 at 18:41
  • To achieve same result instead of triggering event with listeners just manually call all functions you want to run. @Bergi – Frank Jun 22 '22 at 16:13

4 Answers4

14

Events deal with asynchronous operations. They aren't really related to functions in the sense that they are interchangeable.

eventEmitter.on is itself a function, it takes two arguments the event name, then a function (callback) to be executed when the event happens.

eventEmitter.on(evt, callback)

There is no way to tell WHEN the event will be emitted, so you provide a callback to be executed when the event occurs.

In your examples, you are controlling when the events are triggered, which is different than real world use where you may have a server listening for connections that could connect at anytime.

server.listen('9000', function(){
    console.log('Server started');
});

server.on('connection', function(client){
    console.log('New client connected');
    doSomethingWithClient(client);
});

//series of synchronous events
function doSomethingWithClient(client){
    //something with client
}

For server.listen the server doesn't start immediately, once its ready the callback is called

server.on('connection') listens for client connections, they can come at any time. The event is then triggered when a connection occurs, causing the callback to be run.

Then there is doSomethingWithClient this is just a function with a set of synchronous operations to be done when a client connection occurs.

Gabs00
  • 1,869
  • 1
  • 13
  • 12
  • Very helpful. Thank you! – Ariel Weinberger Feb 14 '16 at 18:49
  • 2
    I'm trying to understand this as well. Ok, for your example in the code: `server.on('connection', function(client){ console.log('New client connected'); doSomethingWithClient(client); });` but for this code to be executed some needs to call `event.emit('connection', client)`right? what's the difference of calling a function: `function connection(client){...}` ? – Arthur Mastropietro Mar 06 '20 at 15:57
1

Events useful in webserver code (that is active on port) not in normal scripts, in normal scripts events will behave same as functions because events will be continually active & listening on port for requests as long as port is up so if we use function instead, function will run only once when .js file is ran thus functions cannot capture incoming request and respond.

Example

In this code if you see output of below function dummy_func() triggered immediately when js file is ran & printed statement ConditionReport: A client Connected: 0 only once as output, but the EventReport: A client Connected: printed only when opened http://localhost:58080 in browser and again in another tab if I open same http://localhost:58080 it printed again EventReport: A client Connected: 3

const express = require('express');
const app = express();
const path = require('path');
const PORT = process.env.PORT || 58080;

// Load all static html files in the directory, here index.html file open as default at http://localhost:58080/ but to load html like Resume.html we should call complete http://localhost:58080/Resume.html
app.use(express.static(path.join(__dirname)));

// Configure Port
var server_object=app.listen(PORT, () => console.log("Server listening on port " + PORT));

//Possible incoming Events
var incoming_events=server_object.eventNames()
console.log("\nserver_object:", incoming_events);

//On Event
var i=0
server_object.on('connection',()=>{
    i=i+1
    console.log("\nEventReport: A client Connected:",i);
});

//Using if condition instead of Event
function dummy_func(j){
    console.log("\nConditionReport: A client Connected:",j,"\n");
}

var j=0
if (incoming_events.includes('connection')){
    dummy_func(j)
    j=j+1
}

OUTPUT:

stataraju@statara-ltm7wjr Example2 % node index.js

server_object: [ 'request', 'connection', 'listening' ]

ConditionReport: A client Connected: 0 

Server listening on port 58080

EventReport: A client Connected: 1

EventReport: A client Connected: 2

EventReport: A client Connected: 3
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
sudhir tataraju
  • 1,159
  • 1
  • 14
  • 30
  • if you understand the above the next question will be why I do not use HTTP+functions instead of the event like match path with help of HTTP and run a function :) the answer is, event is useful in case the same action/function is required for multiple paths and we are not sure for which path an action/function suppose to trigger may occur: https://stackoverflow.com/questions/54875234/request-based-vs-event-based-architecture – sudhir tataraju Sep 19 '22 at 15:35
0

I suppose I see the biggest difference I see is that an event emitter could trigger multiple events that are listening, whereas just calling a function only triggers one thing.

So for example, you could have numerous objects in a game that are all waiting for a step event that increments their animation.

They are such a pain to debug though that I'd much rather just use functions.

mczarnek
  • 1,305
  • 2
  • 11
  • 24
  • I can just call multi function at the same time, which is not the privilige of event. – choxsword Jun 21 '21 at 15:56
  • Yeah a step event could just trigger the function. So much modern stuff is just trying to make functions more abstract. To me, classes are just making functions harder to debug. Just have a file with all your connection functions, why make a class? But I only develop small applications. Probably more use for large applications. – Frank Jun 22 '22 at 16:10
-1

An event is an identifier used within tools (.on(), .emit() etc) to set and execute callbacks. Functions are reusable code.

Ini
  • 548
  • 7
  • 19