Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use EventEmitter?

I read a lot of things about EventEmitter. But I do not know in which case I need to use it in my Node.js application.

like image 582
Zagonine Avatar asked Aug 10 '16 18:08

Zagonine


2 Answers

Whenever it makes sense for code to SUBSCRIBE to something rather than get a callback from something. The typical use case would be that there's multiple blocks of code in your application that may need to do something when an event happens.

For example, let's say you are creating a ticketing system. The common way to handle things might be like this:

function addTicket(ticket, callback) {
    insertTicketIntoDatabase(ticket, function(err) {
        if (err)
            return handleError(err);

        callback();
    });
}

But now, someone has decided that when a ticket is inserted into the database, you should email the user to let them know. That's fine, you can add it to the callback:

function addTicket(ticket, callback) {
    insertTicketIntoDatabase(ticket, function(err) {
        if (err)
            return handleError(err);

        emailUser(ticket, callback);
    });
}

But now, someone wants to also notify another system that the ticket has been inserted. Over time, there could be any number of things that should happen when a ticket is inserted. So let's change it around a bit:

function addTicket(ticket, callback) {
    insertTicketIntoDatabase(ticket, function(err) {
        if (err)
            return handleError(err);

        TicketEvent.emit('inserted', ticket);
        callback();
    });
}

We no longer need to wait on all these functions to complete before we notify the user interface. And elsewhere in your code, you can add these functions easily:

TicketEvent.on('inserted', function(ticket) {
    emailUser(ticket);
});

TicketEvent.on('inserted', function(ticket) {
    notifySlack(ticket);
});
like image 67
Chazzu Avatar answered Oct 02 '22 15:10

Chazzu


  • The EventEmitter should be used when the same event can occur multiple times, or may not occur at all. A callback, in fact, is expected to be invoked exactly once, whether the operation is successful or not. Callback means call me when you are ready

  • An API that uses callbacks can notify only one particular callback while using an EventEmitter allows us to register multiple listeners for the same event.

  • Use event emitter if you need to notify the user of a state change.

  • For testing purpose, if you want to make sure a function is called inside a function, emit an event.

like image 27
Yilmaz Avatar answered Oct 02 '22 17:10

Yilmaz