KJ3
KJ3

Reputation: 5298

Node EventEmitters for Common Functions

I was just introduced to node.js's EventEmitters and love the way the code is structured much more that callbacks, and even using libraries like async. I completely understand the basics when there is a simple workflow, i.e.:

this.register = function(email, pass, confirm) {
  var newCustomer = {email:email, pass:pass, confirm: confirm};
  this.emit("newRegistration", newCustomer);
};

var _validate = function(customer{
  this.emit("validated", customer);
};

//...

this.on("newReigstration", _validate);
this.on("validated", _insert);

Makes perfect sense. My question is what to do with functions that are commonly called. For instance, I may have 50 endpoints where I am passed a customer ID, and I need to go and get the customer out of the db, something like this:

Customer.getCustomer(customerId, function(err, customer) {
  // Got the customer, now go do something.
});

I can't just wire up an event to the act of retrieving the customer, because there are 50 different things to be done after "getting the customer". So I couldn't do something like this:

this.on("customerRetrieved", task1);
this.on("customerRetrieved", task2);

this.emit("customerRetrieved", customer); // In getCustomer

Because both would be called, and I only want to call one each time. The only thing I can think of is do something like this:

this.on("customerRetrievedForTask1", task1);
this.on("customerRetrievedForTask2", task2);

But that seems clunky, not to mention dangerous if I accidentally give it the same name as something that already exists. What is the convention for these commonly called functions?

Source of code example

Upvotes: 2

Views: 59

Answers (1)

mattpker
mattpker

Reputation: 119

I don't recommend using EventEmitters for what you are describing. Stick with the callback or promises style for handling this.

Use EventEmitters to watch for events from isolated modules.

A good example of this is a module that makes a connection to some kind of i/o. You don't want to start performing tasks until the connection has been made. Instead of writing a loop to keep checking if the module has made its connection, you just listen for the connection event and then you can continue.

Upvotes: 4

Related Questions